package com.cwits.wifi.ui.fragment;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseFragment;
import com.cwits.wifi.data.beans.BitmapInfo;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.tool.FileUtil;
import com.cwits.wifi.tool.WifiHelper;
import com.cwits.wifi.ui.activity.MainActivity;
import com.cwits.wifi.ui.activity.PhotoActivity;
import com.cwits.wifi.ui.dialog.PhoDialog;
import com.cwits.wifi.ui.dialog.ProgressWindow;
import com.cwits.wifi.ui.dialog.SelectDownDialog;
import com.cwits.wifi.ui.dialog.SelectUpdataDialog;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.ui.dialog.VideoPlayDialog;
import com.cwits.wifi.ui.lib.MjpegView;
import com.cwits.wifi.ui.service.CommunicationService;
import com.cwits.wifi.ui.service.EncodeAVIToMP4Service;
import com.cwits.wifi.ui.view.TLView;
import com.cwits.wifi.util.BitmapCache;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.PreferenceUtils;
import com.cwits.wifi.util.PreferencesHelper;
import com.cwits.wifi.util.TimeFormater;
import com.jieli.lib.stream.beans.StateInfo;
import com.jieli.lib.stream.beans.VideoInfo;
import com.jieli.lib.stream.interfaces.OnBufferingListener;
import com.jieli.lib.stream.interfaces.OnConnectionListener;
import com.jieli.lib.stream.interfaces.OnDownloadListener;
import com.jieli.lib.stream.interfaces.OnPlayStateListener;
import com.jieli.lib.stream.interfaces.OnPlaybackListener;
import com.jieli.lib.stream.interfaces.OnRTStreamListener;
import com.jieli.lib.stream.interfaces.OnRecordListener;
import com.jieli.lib.stream.tools.AVIStreamer;
import com.jieli.lib.stream.tools.AVPlayer;
import com.jieli.lib.stream.tools.AVPlayerException;
import com.jieli.lib.stream.tools.ParseHelper;
import com.jieli.lib.stream.tools.StreamPlayer;
import com.jieli.lib.stream.tools.VideoManager;
import com.jieli.lib.stream.util.ICommon;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;


/**
 *
 * A simple {@link Fragment} subclass.
 */
public class IndexFragment extends BaseFragment implements View.OnClickListener, IAction, ICommon,
        OnPlayStateListener, OnConnectionListener, OnBufferingListener, OnDownloadListener {

    private SelectUpdataDialog selectUpdataDialog;
    private String tag = this.getClass().getName();
    private PowerManager.WakeLock wake_lock;
    private AVPlayer mAVPlayer_RTSP;
    private StreamPlayer mAVPlayer_back;
    private AVIStreamer mAVIStreamer;
    private VideoManager mVideoManager;
    private TLView mScalePanel;
    private View mView;
    private RelativeLayout mRl_Start, mRlBackground, mRlSOS, mRlBottom, index_im_play_rl;
    private LinearLayout mLlNoVideo, mLlPlayBack, mLlLoadSOS, mLlErrorSOS;
    private ImageView mImPhoto, mImNewPlayer, mImSpeed, mImUpdata, mImScreen, mImPlay,mImDisableWifi,mImRealCamera;
    private TextView mTvPbData, mTvPbTime;
    private ImageView mImwin,index_redpoint;
    private ListView mListView;
    private TextView mTvRecordFlag;
    private AlertView mAlertView;
    //private CommandHub mCommandHub;
    private MainApplication mApplication;
    private MjpegView mSurfaceView;
    private AudioManager mAudioManager;
    private MediaPlayer mMediaPlayer;
    private List<VideoInfo> mList;
    private SosInfoAdapter mSosInfoAdapter;
    private boolean isPlaying = false;
    private int width, height;
    private boolean isSOSVisible = true;
    private static int VIDEOMODE = 1;
    private static int PHOTOMODE = 2;
    private boolean isStopped = true;
    private int VIDEOMODE_OR_PHOTOMODE = VIDEOMODE;//说明：1的时候为video模式，2的时候为photo模式
    private boolean isInitialize = false;
    private ProgressDialog pd;
    private Handler mHandler;
    private String mLockSOS = null;
    private boolean isChange = false;
    private VideoInfo mCurrVideoInfo = null;
    private final SimpleDateFormat yyyy_MMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private TextView mTvTime;
    private boolean mIsRTSPPlayer = true;
    private boolean mIsRecording = false;
    private boolean mIsEncording = false;
    private boolean mIsCutRecordImage = false;
    private boolean mIsPhoto = false;
    private boolean mIsGetSOS = false;
    private boolean mIsDevice_Recording = false;
    private boolean mIsDevice_record = false;
    private boolean mMute = false;//是否静音
    private List<String> mRecordList = new ArrayList<String>();
    private String mTarget_PathName = "";
    private RelativeLayout mRlPhoSucess;
    private ImageView mImPhoSucess, mImCanclePho;
    private RelativeLayout mLlCenter;
    private Button mBtnPhoSucess;
    private TextView mTvPhoSucess, mTvErrorSOS;
    private String PHO_SUCESS_PATH = null;
    private String VDO_SUCESS_PATH = null;
    private BitmapCache mBitmapCache;
    private int INDEX_TYPE = 0;
    private int currentDefinition = -1;
    private boolean isRTSOpening = false;
    private boolean isRTSVoiceOpen = false;
    private boolean mIsFirstConnect = false;
    private static boolean mIsPlayBackConnected = false;
    private boolean isUpdataSucess = false;
    private SelectDownDialog selectDownDialog;

    private volatile boolean isBuffering = false;
    private volatile boolean isRequestThumbnail = false;
    private volatile boolean isRequestDownload = false;

    private boolean mIsFirstPlayBackConnected = false;
    private long mFirstTime = 0;
    private boolean mIsStartSOS = false;
    private TwoDialog twoDialog;
    private PhoDialog phoDialog;
    private List<BitmapInfo> bitmapInfoList;
    private BitmapFactory.Options bitmapOptions;
    private static int mFastForward = 1;
    private boolean mGetThumbnail = false;


    private ProgressBar progressBar;
    private long mStartDownloadTime;
    private long mStopDownloadTime;
    private String unLockStr;
    private AlertDialog errorDialog;
    private AlertDialog successDialog;
    private boolean mIsExitDownload = false;
    private boolean mIsCliked_download = false;
    private boolean isSeek = false;
    private boolean mIsUpdateSurfaceView = false;
    private ProgressWindow progressWindow;
    private String mCurrentEncodePath = "";
    private boolean mSwitchRealing = false; //正在切换前后置摄像头
    private boolean mAVPlayReal = false;//当前显示状态，是前置摄像头还是后置摄像头

    public IndexFragment() {
        // Required empty public constructor
    }

    private boolean isBrowseMode = false;
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_SPECIAL_DATA)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_SPECIAL_STATE);
                String param1 = stateInfo.getParam()[0];

                String cmdResult = stateInfo.getCmdNumber();
                switch (cmdResult) {
                    case CMD_DEVICE_MODE:
                        /*
                        mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_GET_RECORDING_STATUS);
                        switch (param1) {
                            case ARGS_VIDEO_MODE: {

                                switch (CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS)) {
                                    case ARGS_NO_RECORDING:
                                        //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_START_RECORD, ARGS_START_RECORD);
                                        //startFlick(mTvRecordFlag);
                                        mIsDevice_Recording = false;
                                        break;
                                    case ARGS_IN_RECORDING:
                                        //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                                        //stopFlick(mTvRecordFlag);
                                        mIsDevice_Recording = true;
                                        break;
                                    default:
                                        mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_GET_RECORDING_STATUS);
                                        break;
                                }
                                break;
                            }
                            case ARGS_PHOTO_MODE:
                                //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_TAKE_PHOTO, ARGS_TAKE_PHOTO);


                                break;
                            case ARGS_PLAY_MODE:
                                break;
                            case ARGS_USB_MODE:
                                break;
                            default:
                                break;
                        }*/
                        break;
                    case CMD_RESET_DEVICE:
                        /**Get current mode status after reset device*/
                        ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_MODE);
                        break;
                    case CMD_SDCARD_STATE:
                        break;
                    case CMD_BATTERY_STATE:

                        break;
                    case CMD_TAKE_PHOTO:
                        //shootSound();

                        break;
                    case CMD_START_RECORD:
                        if(!mIsDevice_Recording){
                            mIsDevice_Recording = true;
                            mHandler.post(RedPointRunnable);
                        }

                        break;
                    case CMD_STOP_RECORD:
                        mIsDevice_Recording = false;
                        mHandler.removeCallbacks(RedPointRunnable);

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                index_redpoint.setVisibility(View.GONE);
                            }
                        });

                        if (mIsDevice_record) {
                            if (!isBrowseMode) {
                                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        createBackPlayer();
                                        mIsRTSPPlayer = false;
                                        mHandler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                mImPlay.setVisibility(View.VISIBLE);
                                            }
                                        });
                                        mHandler.removeCallbacks(RTSPRunnable);
                                        mHandler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                mScalePanel.setLock(false);
                                            }
                                        }, 1000);

                                    }
                                }, 500);

                            }
                        }
                        break;
                    case CMD_TIMER_PICTURE:
                        break;
                    case CMD_DELETE_FILE:
                    case CMD_DELETE_ALL:
                        break;
                    case CMD_VIDEO_PICTURE_QUALITY:
                        break;
                    case CMD_PHOTO_SIZE:

                        break;
                    case CMD_WHITE_BALANCE:

                        break;
                    case CMD_CONTINUOUS_SHOOTING:

                        break;
                    case CMD_VIDEO_SIZE:

                        break;
                    case CMD_METERING:
                        break;
                    case CMD_GET_RECORDING_STATUS:
                        switch (param1) {
                            case ARGS_NO_RECORDING:
                                mIsDevice_Recording = false;
                                break;
                            case ARGS_IN_RECORDING:
                                mIsDevice_Recording = true;
                                break;
                        }
                        break;
                    case CMD_TIMER_PICTURE_STATUS:
                        break;
                    case CMD_ENTER_BROWSING_MODE:
                        if(mAVPlayReal){
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                        }else{
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                        }
                        mImRealCamera.setVisibility(View.GONE);
                        if (getActivity() == null) {
                            Dbug.e(tag, "getActivity() is null");
                            return;
                        }
                        int count = Integer.parseInt(param1);
                        Dbug.d("BrowseFileActivity", " =CMD_ENTER_BROWSING_MODE= count : " + count);
                        if (count < 0) {
//                                showToastLong(getString(R.string.please_wait));
                            mApplication.setAllowBrowseDev(false);
                            return;
                        } else {
                            mApplication.setAllowBrowseDev(true);
                        }
                        isBrowseMode = true;

                        break;
                    case CMD_EXIT_BROWSING_MODE:
                        Dbug.d(tag, "CMD_EXIT_BROWSING_MODE------------------:");
                        isBrowseMode = false;
                        tryToPlay();
                        break;
                    case CMD_RT_STREAM_OPEN:
                        if (mAVPlayer_RTSP == null || mAVPlayer_RTSP.isRearStreamPlaying()){
                            Dbug.w(tag, "Rear view is playing.");
                            return;
                        }
                        Dbug.e(tag, "CMD_RT_STREAM_OPEN success....................");
                        if (ARGS_RT_STREAM_OPEN_SUCCESS.equals(param1)) {
                            Dbug.e(tag, "CMD_RT_STREAM_OPEN success....................");
//                                isRTSPlaying = true;
                            displayZhiboView_visiable();
                            //mScalePanel.setLock(false);
                            if (stateInfo.getParam().length <= 1) {
                                Dbug.e(tag, "param2 not exit");
                                return;
                            }
                            String param2 = stateInfo.getParam()[1];
                            Dbug.i(tag, "CMD_RT_STREAM_OPEN success...................param2=" + param2);
                            if (TextUtils.isEmpty(param2)) {
                                Dbug.e(tag, "param2 not exit");
                                return;
                            }
                            switch (param2) {
                                case ARGS_RT_STREAM_OPEN_FLUENCY:
                                    currentDefinition = 0;
                                    break;
                                case ARGS_RT_STREAM_OPEN_SD:
                                    currentDefinition = 1;
                                    break;
                                case ARGS_RT_STREAM_OPEN_HD:
                                    currentDefinition = 2;
                                    break;
                                default:
                                    Dbug.e(tag, "CMD_RT_STREAM_OPEN fail");
                                    break;
                            }
                            if (mAVPlayer_RTSP != null) {
                                mAVPlayer_RTSP.setOnRTStreamListener(onRTStreamListener);
                            }
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mTvTime.setVisibility(View.VISIBLE);
                                    postDispalyDragAndZoom();
                                }
                            });
                            if (stateInfo.getParam().length <= 2) {
                                isRTSOpening = true;
                                //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_CONTROL_RTS_VOICE);
                                Dbug.e(tag, "param3 not exit");
                                return;
                            }
                            String param3 = stateInfo.getParam()[2];
                            if (TextUtils.isEmpty(param3)) {
                                Dbug.e(tag, "param3 is empty!");
                                return;
                            }
                            switch (param3) {
                                case ARGS_RT_STREAM_CLOSED:
                                    isRTSOpening = false;
                                    break;
                                case ARGS_RT_STREAM_OPENED:
                                    isRTSOpening = true;
                                    break;
                            }
                            Dbug.i(tag, "CMD_RT_STREAM_OPEN param3 =" + param3 + ".......currentDefinition : " + currentDefinition
                                    + " .........isRTSOpening=" + isRTSOpening);
                            if (currentDefinition > -1) {
                                updateDefinition(currentDefinition, false);
                            }
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_GET_RECORDING_STATUS);
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_CONTROL_RTS_VOICE, ARGS_CLOSE_RTS_VOICE);
                            //mIsGetSOS = true;
                        } else {
                            Dbug.w(tag, "CMD_RT_STREAM_OPEN fail");
                            if (stateInfo.getParam().length <= 1) {
                                Dbug.e(tag, "param2 not exit");
                                return;
                            }
                            String param2 = stateInfo.getParam()[1];
                            Dbug.i(tag, "CMD_RT_STREAM_OPEN failed...................param2=" + param2);
                            if (TextUtils.isEmpty(param2)) {
                                Dbug.e(tag, "param2 is empty!");
                                return;
                            }
                            boolean isSetCmd;
                            switch (param2) {
                                case ARGS_RT_STREAM_OPEN_FLUENCY:
                                case ARGS_RT_STREAM_OPEN_SD:
                                case ARGS_RT_STREAM_OPEN_HD:
                                    isSetCmd = false;
                                    break;
                                default:
                                    isSetCmd = true;
                                    Dbug.e(tag, "CMD_RT_STREAM_OPEN fail");
                                    break;
                            }
                            if (isSetCmd) {
                                if (currentDefinition > -1) {
                                    updateDefinition(currentDefinition, true);
                                }
                            }
                        }
                        break;
                    case CMD_REAR_RTS_OPEN:
                        if (mAVPlayer_RTSP.isRearStreamPlaying()){
                            if (mAVPlayer_RTSP != null) {
                                mAVPlayer_RTSP.setOnRTStreamListener(onRTStreamListener);
                            }
                        } else {
                            if (mAVPlayer_RTSP.isFrontStreamPlaying()){
                                Dbug.w(tag, "Front view is playing.");
                                return;
                            }
                            int resolution = Integer.parseInt(stateInfo.getParam()[3]);
                            Dbug.w(tag, "resolution = " + resolution);
                            String value = ARGS_RT_STREAM_VGA;
                            switch (resolution){
                                case 640:
                                    value = ARGS_RT_STREAM_VGA;
                                    break;
                                case 720:
                                    value = ARGS_RT_STREAM_720P;
                                    break;
                            }
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_RTS_OPEN, stateInfo.getParam()[1], value);
                        }
                        break;
                    case CMD_REAR_RTS_CLOSE:
                    case CMD_RT_STREAM_CLOSE:
                        if (ARGS_RT_STREAM_CLOSE_SUCCESS.equals(param1)){
//                                isRTSOpening = false;
                            if (mSwitchRealing) {
                                mSwitchRealing = false;
                                if (CMD_REAR_RTS_CLOSE.equals(cmdResult)) {
                                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_OPEN, "0", 0 + "");
                                    mAVPlayReal = false;
                                    mLlLoadSOS.setVisibility(View.VISIBLE);
                                    mListView.setVisibility(View.GONE);
                                    mRlSOS.setVisibility(View.GONE);
                                    handler1.removeMessages(2222);
                                    handler1.sendEmptyMessageDelayed(2222, 15000);
                                    mLlNoVideo.setVisibility(View.GONE);
                                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                                } else if (CMD_RT_STREAM_CLOSE.equals(cmdResult)){
                                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_RTS_OPEN, ARGS_RT_STREAM_OPEN_FLUENCY, 0 + "");
                                    mAVPlayReal = true;
                                    mLlLoadSOS.setVisibility(View.VISIBLE);
                                    handler1.removeMessages(2222);
                                    handler1.sendEmptyMessageDelayed(2222, 15000);
                                    mListView.setVisibility(View.GONE);
                                    mLlNoVideo.setVisibility(View.GONE);
                                    mRlSOS.setVisibility(View.GONE);
                                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                                }
                            }else{
                                if (mAVPlayer_RTSP != null) {
                                    mAVPlayer_RTSP.setOnRTStreamListener(null);
                                }
                            }

                        } else {
                            Dbug.w(tag, "CMD_RT_STREAM_CLOSE fail");
                        }
                        break;
                    case CMD_CONTROL_RTS_VOICE:
                        if (ARGS_CONTROL_RTS_VOICE_SUCCESS.equals(param1)) {
                            if (stateInfo.getParam().length <= 1) {
                                Dbug.e(tag, "param2 not exit");
                                return;
                            }
                            String param2 = stateInfo.getParam()[1];
                            switch (param2) {
                                case ARGS_CLOSE_RTS_VOICE_STATE:
                                    isRTSVoiceOpen = false;
                                    break;
                                case ARGS_OPEN_RTS_VOICE_STATE:
                                    isRTSVoiceOpen = true;
                                    break;
                            }
                        } else {
                            Dbug.e(tag, "CMD_CONTROL_RTS_VOICE failed!");
                        }
                        break;
                    case CMD_VIDEO_START_PLAYBACK:
                    case CMD_REAR_VIDEO_PLAYBACK_START:

                        if (stateInfo.getParam().length >= 2) {
                            if (TextUtils.isEmpty(stateInfo.getParam()[1])) {
                                return;
                            }
                            int rate = Integer.parseInt(stateInfo.getParam()[1]);
                            int mFrameRate = 1000000 / rate;
                            Dbug.i(tag, "param2=" + rate + ", mFrameRate=" + mFrameRate);

                            if (ARGS_VIDEO_START_DOWNLOAD.equals(stateInfo.getParam()[4])) {
                                initAVIStream();
                                startRecording();
                            }
                        } else {
                            if (stateInfo.getParam().length == 1) {
                                Dbug.i(tag, "param1=" + stateInfo.getParam()[0]);
                            }
                            Dbug.e(tag, "stateInfo.getParam().length=" + stateInfo.getParam().length);
                        }
                        break;
                    default:
                        Dbug.e(tag, "error:cmdResult= " + cmdResult);
                        break;
                }

            } else if (action.equals(ACTION_DEVICE_CONNECTION_SUCCESS)) {
                Dbug.i(tag, "ACTION_DEVICE_CONNECTION_SUCCESS:");
                syncDeviceStatus();
                //mStreamPlayer.initSurface(mCameraSurface.getHolder());
            } else if (ACTION_DEVICE_LANG_CHANGED.equals(action)) {

            } else if (ACTION_GET_RECORDING_STATUS.equals(action)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GET_RECORDING_STATUS);
                String param1 = stateInfo.getParam()[0];
                switch (param1) {
                    case ARGS_NO_RECORDING:
                        mIsDevice_Recording = false;
                        mHandler.removeCallbacks(RedPointRunnable);

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                index_redpoint.setVisibility(View.GONE);
                            }
                        });
                        break;
                    case ARGS_IN_RECORDING:
                        if(!mIsDevice_Recording){
                            mIsDevice_Recording = true;
                            mHandler.post(RedPointRunnable);
                        }

                        break;
                }

            } else if (ACTION_RESPONDING_VIDEO_DESC_REQUEST.equals(action)) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //设置时间块数据
                        mScalePanel.SetCalStuff(ParseHelper.getInstance().getSortedVideos());
                        mScalePanel.setLock(false);
                        if (mList.size() == 0) {
                            List<VideoInfo> vf = ParseHelper.getInstance().getSortedVideos();
                            mList.clear();
                            for (int i = 0; i < vf.size(); i++) {
                                if (vf.get(i).getIsLocked())
                                    mList.add(vf.get(i));
                            }
                            //mSosInfoAdapter.notifyDataSetChanged();
                            showSOSList(mList.size());
                            mIsGetSOS = false;
                        }else{

                            List<VideoInfo> vf = ParseHelper.getInstance().getSortedVideos();
                            mList.clear();
                            for (int i = 0; i < vf.size(); i++) {
                                if (vf.get(i).getIsLocked())
                                    mList.add(vf.get(i));
                            }
                            //mSosInfoAdapter.notifyDataSetChanged();
                            showSOSList(mList.size());
                            mIsGetSOS = false;
                        }
                    }
                });
                if (mIsFirstConnect) {
                    mIsFirstConnect = false;
                    if (isBrowseMode)
                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_EXIT_BROWSING_MODE, ARGS_EXIT_BROWSING_MODE);
                }
            } else if (ACTION_VIDEO_FILE_END.equals(action)) {
                String filePath = intent.getStringExtra(KEY_VIDEO_FILE_END);
                if (!TextUtils.isEmpty(filePath)) {
                    String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                    showToast(fileName);
                }
            } else if (ACTION_RELEASE_SOSSTORAGE_INFO.equals(action)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_RELEASESOSSTORAGE_INFO);
                String state = stateInfo.getParam()[0];
                if (state.equals("0")) {
                    //error
                    showToastLong(getString(R.string.stor_lock_err));
                } else if (state.equals("1")) {
                    //sucess
                    if (mLockSOS != null) {
                        for (int i = 0; i < mList.size(); i++) {
                            if (mList.get(i).getFileName().equals(mLockSOS)) {
                                mList.remove(i);
                            }
                        }
                    }
                    showToastLong(getString(R.string.stor_lock_sucess));
                    if (mList.size() == 0) {
                        handler1.sendEmptyMessage(0002);
                    } else {
                        mSosInfoAdapter.notifyDataSetChanged();
                    }
                }
            } else if (action.equals(ACTION_GET_VERSION_INFO)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GET_VERSION_INFO);
                PreferencesHelper.putStringValue(context.getApplicationContext(), "soft_id", stateInfo.getParam()[0]);
                checkSoft(stateInfo.getParam()[0]);
            } else if (action.equals(ACTION_GET_DEVICE_INFO)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GETDEVICE_INFO);
                PreferencesHelper.putStringValue(context.getApplicationContext(), "device_id", stateInfo.getParam()[0]);
            }else if(action.equals(ACTION_ENCORDING_CURRENT_START)){
                //do nothing
                mCurrentEncodePath = intent.getStringExtra(ACTION_ENCORDING_CURRENT_START);
                if(progressWindow != null&&mCurrentEncodePath.equals(VDO_SUCESS_PATH)){
                    progressWindow.setTvTitle(getString(R.string.dialog_updata_sucess));
                    progressWindow.startProgress(1);
                }
            }else if(action.equals(ACTION_ENCORDING_CURRENT_END)){
                String current_encode_path = intent.getStringExtra(ACTION_ENCORDING_CURRENT_END);
                if(progressWindow != null&&current_encode_path.equals(VDO_SUCESS_PATH)){
                    progressWindow.setProgress(100);
                    progressWindow.setPlayColor(Color.parseColor("#02acfa"));
                    progressWindow.setTvTitle(getString(R.string.dialog_zm_sucess));
                }
            }
            else if(action.equals(ACTION_REVERSING_STATE)){
                StateInfo reversingStateInfo = (StateInfo) intent.getSerializableExtra(KEY_REVERSING_STATE);
                Dbug.i("ACTION_REVERSING_STATE:","ACTION_REVERSING_STATE，code:" + ACTION_REVERSING_STATE + "reversingStateInfo:" + reversingStateInfo);
                if(reversingStateInfo != null) {
                    if (reversingStateInfo.getParam().length >= 1) {
                        String reversingState = reversingStateInfo.getParam()[0];
                        switch(reversingState){
                            case "0":
                                if(mSwitchRealing)
                                    return;
                                if(mApplication.getRealCamera()){
                                    if(mIsRTSPPlayer){
                                        if(mAVPlayer_RTSP.isRearStreamPlaying()){
                                            //直播模式
                                            mSwitchRealing = true;
                                            mScalePanel.setLock(true);
                                            //先关闭后视流，再启动前视流
                                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_RTS_CLOSE, ARGS_REAR_RTS_CLOSE);
                                        }
                                    }
                                }
                                break;
                            case "1":
                                if(mSwitchRealing)
                                    return;
                                if(mApplication.getRealCamera()){
                                    if(mIsRTSPPlayer){
                                        if(mAVPlayer_RTSP.isFrontStreamPlaying()){
                                            //直播模式
                                            mSwitchRealing = true;
                                            mScalePanel.setLock(true);
                                            //先关闭前视流，再启动后视流
                                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_CLOSE, ARGS_RT_STREAM_CLOSE);
                                        }
                                    }
                                }
                                break;
                        }

                    }
                }
            }
        }
    };

    private void checkSoft(String soft_id) {
        String download_name = PreferencesHelper.getSharedPreferences(this.getActivity().getApplicationContext()).getString("downLoad_soft_id", "xxx");
        if (download_name.equals("xxx") == false && download_name.equals(soft_id) == false && download_name.startsWith(SOFT_ID_STARTNAME) && soft_id.startsWith(SOFT_ID_STARTNAME)) {
            //需要更新固件
            if (mApplication.isSdcardState())
                ((MainActivity) (this.getActivity())).uploadSoft();
        } else if (download_name.equals(soft_id)
                && PreferencesHelper.getSharedPreferences(this.getActivity().getApplicationContext()).getString("downLoad_soft_path", "xxx").equals("xxx") == false) {
            deleteFile(PreferencesHelper.getSharedPreferences(this.getActivity().getApplicationContext()).getString("downLoad_soft_path", "xxx"));
            PreferencesHelper.putStringValue(this.getActivity().getApplicationContext(), "downLoad_soft_id", "xxx");
        }
    }

    private void postDispalyDragAndZoom() {
        if (!PreferencesHelper.getSharedPreferences(this.getActivity().getApplicationContext()).getBoolean("drag_zoom_fill", false)) {
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    displayDragAndZoom();
                }
            }, 1500);
        }
    }

    private void displayDragAndZoom() {
        if (PreferencesHelper.getSharedPreferences(this.getActivity().getApplicationContext()).getBoolean("drag_zoom_fill", false))
            return;
        if (this.getActivity() instanceof MainActivity) {
            ((MainActivity) (this.getActivity())).displayDragOrZoomoutIn();
            PreferencesHelper.putBooleanValue(this.getActivity().getApplicationContext(), "drag_zoom_fill", true);
        }

    }

    public void displayScalePanel() {
        if (mScalePanel.getVisibility() == View.GONE) {
            // mScalePanel.setVisibility(View.VISIBLE);
            //  mZhiBo_Seek.setVisibility(View.GONE);
        }
    }

    public void displayNoSdcard() {
        showToastLong(getString(R.string.index_no_sd));
        mScalePanel.SetCalStuff(null);
        mList.clear();
        isSOSVisible = false;
        mLlErrorSOS.setVisibility(View.VISIBLE);
        mLlLoadSOS.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);
        mLlNoVideo.setVisibility(View.GONE);
        mRlSOS.setVisibility(View.GONE);
        mScalePanel.setExistSdcard(false);


    }

    private void showSOSList(int size) {
        mLlErrorSOS.setVisibility(View.GONE);
        if (size != 0) {
            handler1.sendEmptyMessage(0001);
        } else {
            handler1.sendEmptyMessage(0002);
        }

    }

    private void updateDefinition(int position, boolean onlyUI) {
        if (getActivity() == null || position < 0) {
            return;
        }
        /**Update spinner selection*/
        Dbug.i(tag, "updateDefinition setSelection = " + position);
        //mStreamPlayModeSpinner.setTag(position);
        String definition = "";
        switch (position) {
            case 0:
                definition = ARGS_RT_STREAM_OPEN_FLUENCY;
                break;
            case 1:
                definition = ARGS_RT_STREAM_OPEN_SD;
                break;
            case 2:
                definition = ARGS_RT_STREAM_OPEN_HD;
                break;
        }
        if (!onlyUI) {
            if (!isRTSOpening) {
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_OPEN, definition);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_index, container, false);
        PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        wake_lock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, tag);
        wake_lock.setReferenceCounted(false);
        wake_lock.acquire();
        mHandler = new Handler();

        mFastForward = 1;

        init();
        initView();
        createTempFile();

        return mView;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // land do nothing is ok////
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (mIsRTSPPlayer == false && mIsUpdateSurfaceView) {
                mSurfaceView.setUpdateCanvas(true);
            }
            params.height = width / 5 * 4;
            params.width = height;
            mSurfaceView.setLayoutParams(params);
            mRlBackground.setLayoutParams(params);
            RelativeLayout.LayoutParams tlVideo = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, width / 5);
            //tlVideo.width = height;
            tlVideo.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            //mScalePanel.setBackgroundColor(Color.GRAY);
            // mZhiBo_Seek.setVisibility(View.GONE);
            mScalePanel.setLayoutParams(tlVideo);
            // mScalePanel.setVisibility(View.VISIBLE);
            mRlBottom.setVisibility(View.GONE);
            mImUpdata.setVisibility(View.GONE);

        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // port do nothing is ok
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            //mScalePanel.setVisibility(View.GONE);
            params.height = width * 9 / 16;

            params.width = width;

            mRlBackground.setLayoutParams(params);
            mRlBottom.setVisibility(View.VISIBLE);
            if (mIsRTSPPlayer) {
                mImUpdata.setVisibility(View.GONE);
            } else {
                mImUpdata.setVisibility(View.VISIBLE);
            }

        }
    }


    private void initView() {

        System.out.print(width + "----" + height);
        WindowManager wm = (WindowManager) this.getActivity()
                .getSystemService(Context.WINDOW_SERVICE);

        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);


        params.height = width * 9 / 16;

        params.width = width;

        //mSurfaceView.setWidthAndHeight(width,width*9/16);
        mRlBackground.setLayoutParams(params);
    }

    private void displayPlayBackView_visiable() {
        mImSpeed.setVisibility(View.VISIBLE);
        mImNewPlayer.setVisibility(View.VISIBLE);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mImUpdata.setVisibility(View.GONE);
        } else {
            mImUpdata.setVisibility(View.VISIBLE);
        }
    }

    private void displayPlayBackView_gone() {
        mImSpeed.setVisibility(View.GONE);
        mImNewPlayer.setVisibility(View.GONE);
        mImUpdata.setVisibility(View.GONE);
    }

    private void displayZhiboView_visiable() {
        mImPhoto.setVisibility(View.VISIBLE);
        mImScreen.setVisibility(View.VISIBLE);
        mImDisableWifi.setVisibility(View.VISIBLE);
    }

    private void displayZhiboView_gone() {
        mImPhoto.setVisibility(View.GONE);
        mImScreen.setVisibility(View.GONE);
        mImDisableWifi.setVisibility(View.GONE);
    }

    private void init() {
        mApplication = (MainApplication) this.getActivity().getApplication();

        mLlPlayBack = (LinearLayout) mView.findViewById(R.id.index_ll_playback);
        progressBar = (ProgressBar) mView.findViewById(R.id.progressBar);

        mImPhoto = (ImageView) mView.findViewById(R.id.index_im_photo);
        mImScreen = (ImageView) mView.findViewById(R.id.index_im_full_screen);
        mImRealCamera = (ImageView) mView.findViewById(R.id.index_im_realcamera);
        mImSpeed = (ImageView) mView.findViewById(R.id.index_im_2x);
        mImNewPlayer = (ImageView) mView.findViewById(R.id.index_im_new_play);
        mImUpdata = (ImageView) mView.findViewById(R.id.index_im_load);
        mImPlay = (ImageView) mView.findViewById(R.id.index_im_play);
        mImDisableWifi = (ImageView) mView.findViewById(R.id.index_im_disable_wifi);
        index_redpoint = (ImageView) mView.findViewById(R.id.index_redpoint);
        mImPhoto.setOnClickListener(this);
        mImScreen.setOnClickListener(this);
        mImRealCamera.setOnClickListener(this);
        mImSpeed.setOnClickListener(this);
        mImNewPlayer.setOnClickListener(this);
        mImUpdata.setOnClickListener(this);
        mImDisableWifi.setOnClickListener(this);
        //mImPlay.setOnClickListener(this);

        index_im_play_rl = (RelativeLayout) mView.findViewById(R.id.index_im_play_rl);
        index_im_play_rl.setOnClickListener(this);
        mRlPhoSucess = (RelativeLayout) mView.findViewById(R.id.index_rl_pho_sucess);
        mImPhoSucess = (ImageView) mView.findViewById(R.id.index_im_pho_sucess);
        mImCanclePho = (ImageView) mView.findViewById(R.id.index_im_cancle_pho_sucess);
        mBtnPhoSucess = (Button) mView.findViewById(R.id.index_btn_pho_sucess);
        mTvPhoSucess = (TextView) mView.findViewById(R.id.index_tv_pho_sucess);

        mRlBottom = (RelativeLayout) mView.findViewById(R.id.index_rl_bottom);
        mTvPbData = (TextView) mView.findViewById(R.id.index_tv_playback_data);
        mTvTime = (TextView) mView.findViewById(R.id.index_tv_time);
        mTvPbTime = (TextView) mView.findViewById(R.id.index_tv_playback_time);
        mRlBackground = (RelativeLayout) mView.findViewById(R.id.index_rl_win_background);
        mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        mLlNoVideo = (LinearLayout) mView.findViewById(R.id.index_ll_no_video);
        mLlLoadSOS = (LinearLayout) mView.findViewById(R.id.index_ll_load_sos);
        mTvErrorSOS = (TextView) mView.findViewById(R.id.index_tv_error_video);
        mLlCenter = (RelativeLayout) mView.findViewById(R.id.index_ll_btn_background);
        mTvErrorSOS.setOnClickListener(this);
        mLlErrorSOS = (LinearLayout) mView.findViewById(R.id.index_ll_error_video);
        mRlSOS = (RelativeLayout) mView.findViewById(R.id.index_tv_background);
        mTvRecordFlag = (TextView) mView.findViewById(R.id.index_record_flag);
        mRl_Start = (RelativeLayout) mView.findViewById(R.id.index_rl_win_btn);
        mImwin = (ImageView) mView.findViewById(R.id.index_im_win);
        mSurfaceView = (MjpegView) mView.findViewById(R.id.container1);
        mScalePanel = (TLView) mView.findViewById(R.id.huifang_play);
        mScalePanel.setOnValueChangeListener(onValueChangeListener);
        mScalePanel.setLock(true);
        mVideoManager = VideoManager.getInstance();
        mSurfaceView.setOnClickListener(this);
        mListView = (ListView) mView.findViewById(R.id.index_lv_sos);
        initList();
        mSosInfoAdapter = new SosInfoAdapter();
        mListView.setAdapter(mSosInfoAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mIsRecording) {
                    showToastLong(getString(R.string.index_update_video));
                    return;
                }
                //SOS跳转播放
                if (mScalePanel.getVisibility() == View.GONE) {
                    //  mScalePanel.setVisibility(View.VISIBLE);
                    // mZhiBo_Seek.setVisibility(View.GONE);
                    if (mIsRTSPPlayer == true) {
                        mIsGetSOS = false;
                        if(mAVPlayReal){
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                        }else{
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                        }
                    }
                }

                mCurrVideoInfo = mList.get(position);
                if (mIsRTSPPlayer == true) {
                    mIsRTSPPlayer = false;
                    //if (mIsDevice_Recording)
                    Dbug.d(tag, "recordState:" + "---mIsDevice_Recording--setOnClickListener-----");
                    //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                    tryToStop();
                    destroyRTSPPlayer();
                    mTvTime.setText(getString(R.string.index_hf));
                    mScalePanel.setLock(true);
                    //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                    String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                    Dbug.d(tag, "recordState:" + recordState);
                    if (ARGS_IN_RECORDING.equals(recordState)) {
                        mIsDevice_record = true;
                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                        mIsFirstPlayBackConnected = true;
                        mIsStartSOS = true;
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                mImPlay.setVisibility(View.VISIBLE);
                                mScalePanel.setTimeOffset(mCurrVideoInfo.getStartTime().getTimeInMillis());
                            }
                        });
                        /*
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!isBrowseMode) {
                                    CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Dbug.d(tag, "recordState:" + "---sos_first--setOnClickListener-----");
                                            mIsFirstPlayBackConnected = true;
                                            mIsStartSOS = true;
                                            createBackPlayer();
                                            Dbug.d(tag, "recordState:" + "---sos_first--createBackPlayer-----");
                                            mHandler.removeCallbacks(RTSPRunnable);
                                        }
                                    }, 500);

                                }
                            }
                        }, 300);
                        mIsDevice_record = true;
                        */
                    } else {
                        if (!isBrowseMode) {
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Dbug.d(tag, "recordState:" + "---sos_first--setOnClickListener-----");
                                    mIsFirstPlayBackConnected = true;
                                    mIsStartSOS = true;
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {

                                            mImPlay.setVisibility(View.VISIBLE);
                                            mScalePanel.setTimeOffset(mCurrVideoInfo.getStartTime().getTimeInMillis());
                                        }
                                    });
                                    createBackPlayer();
                                    Dbug.d(tag, "recordState:" + "---sos_first--createBackPlayer-----");
                                    mHandler.removeCallbacks(RTSPRunnable);
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mScalePanel.setLock(false);
                                        }
                                    }, 1000);

                                }
                            }, 2500);


                        }
                    }
                    displayPlayBackView_visiable();

                } else {

                    if (mScalePanel.getLock()) {
                        showToast(getString(R.string.index_hf));
                        return;
                    }

                    if (!mIsPlayBackConnected) {
                        Dbug.e(tag, "onValueChangeEnd: disconnected!!");
                        showToastLong(getString(R.string.index_wait_hc));
                        return;
                    }
                    if (mGetThumbnail)
                        return;
                    if (mAVPlayer_back != null && (mAVPlayer_back.isPlaying() || mAVPlayer_back.isPaused())) {
                        //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_STOP, ARGS_VIDEO_STOP);
                        Dbug.d(tag, "recordState:" + "---sos_first--connect-----");
                        if (!isSeek) {
                            isSeek = true;
                            mIsPlayBackConnected = false;
                            mAVPlayer_back.disconnect();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mImPlay.setVisibility(View.VISIBLE);
                                    mScalePanel.setTimeOffset(mCurrVideoInfo.getStartTime().getTimeInMillis());
                                }
                            });
                            isPlaying = false;
                            isStopped = true;

                            if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                                mGetThumbnail = true;
                                String deviceip= AP_MODE_DEVICE_IP;
                                if(WifiHelper.getInstance(IndexFragment.this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                                    deviceip = ((MainActivity)(IndexFragment.this.getActivity())).device_ip;
                                if(mAVPlayReal){
                                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                                }else{
                                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                                }
                            }
                        }
                        isPlaying = false;
                        isStopped = true;
                    } else {
                        //mAVPlayer_back.disconnect();
                        Dbug.d(tag, "recordState:" + "---sos_first--tryToStartPlayback-----");
                        if (!isSeek) {
                            //isSeek = true;
                            //mIsPlayBackConnected = false;
                            //mAVPlayer_back.disconnect();
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mImPlay.setVisibility(View.VISIBLE);
                                    mScalePanel.setTimeOffset(mCurrVideoInfo.getStartTime().getTimeInMillis());
                                }
                            });

                            if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                                mGetThumbnail = true;
                                String deviceip= AP_MODE_DEVICE_IP;
                                if(WifiHelper.getInstance(IndexFragment.this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                                    deviceip = ((MainActivity)(IndexFragment.this.getActivity())).device_ip;
                                if(mAVPlayReal){
                                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                                }else{
                                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                                }
                            }
                        }
                        isPlaying = false;
                        isStopped = true;
                    }
                }


            }
        });

        //initView();
        mBtnPhoSucess.setOnClickListener(this);
        mImCanclePho.setOnClickListener(this);
        mRl_Start.setOnClickListener(this);
        initAVIStream();
        isStopped = true;
        isPlaying = false;
        mIsEncording = false;
        bitmapInfoList = new ArrayList<BitmapInfo>();
        bitmapOptions = new BitmapFactory.Options();
//        bitmapOptions.inSampleSize = 2;
//        bitmapOptions.inScaled = false;
//        bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
        //noinspection deprecation
        bitmapOptions.inPurgeable = true;
    }

    private void initList() {
        //
        mList = new ArrayList<VideoInfo>();
    }

    public void displayVideo() {
        //mScalePanel.setLock(false);
        mSurfaceView.setVisibility(View.VISIBLE);
        mRl_Start.setVisibility(View.GONE);
        mImwin.setVisibility(View.GONE);
        //mCommandHub = CommandHub.getInstance();
        mLlLoadSOS.setVisibility(View.VISIBLE);
        handler1.sendEmptyMessageDelayed(2222, 15000);
        mLlNoVideo.setVisibility(View.GONE);

        /*Get SDCard state*/
        ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_SDCARD_STATE);
        /**Get device's UUID*/
        ControlManager.getInstance().requestStatus(ICommon.CTP_ID_DEFAULT, CMD_DEVICE_UUID);
        //获取版本信息
        ControlManager.getInstance().sendCommand("2", "0550", "0");
        ControlManager.getInstance().sendCommand("2", "0551", "0");
        createRTSPPlayer();
        mHandler.post(RTSPRunnable);
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                if(mAVPlayReal){
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                }else{
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                }
            }
        }, 1000);
        /*
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                mIsFirstConnect = true;
                String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                Dbug.d(tag, "recordState:" + recordState);
                if (ARGS_IN_RECORDING.equals(recordState)) {
                    CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                            mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                        }
                    }, 1500);
                } else {
                    mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                    mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                }

            }
        }, 2000);
        */


        Dbug.i(tag, "Create ---222-----");

        //mStreamPlayer.play();
//        changeFragment(R.id.container1, new CameraFragment());
    }

    @Override
    public void onWiFiState(boolean isAutoDisabled, int WiFi_state) {
        switch (WiFi_state) {
            case 1://已连接上，可以使用
                break;
            case 2://断开，无法使用
                //connectError();
                mIsRTSPPlayer = true;
                mAVPlayReal = false;
                mSwitchRealing = false;
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    toVertical();
                }
                mIsDevice_Recording = false;
                mHandler.removeCallbacks(RedPointRunnable);

                index_redpoint.setVisibility(View.GONE);
                mScalePanel.SetCalStuff(null);
                mLlErrorSOS.setVisibility(View.GONE);
                destroyBackPlayer();
                destroyRTSPPlayer();
                mSurfaceView.setVisibility(View.GONE);
                mRl_Start.setVisibility(View.VISIBLE);
                mImwin.setVisibility(View.VISIBLE);
                mScalePanel.setLock(true);
                displayPlayBackView_gone();
                displayZhiboView_gone();
                mImUpdata.setVisibility(View.GONE);
                mImRealCamera.setVisibility(View.GONE);
                mImPlay.setVisibility(View.INVISIBLE);
                //mScalePanel.setVisibility(View.GONE);
                // mZhiBo_Seek.setVisibility(View.VISIBLE);
                mList.clear();
                mIsExitDownload = false;
                bitmapInfoList.clear();
                mSosInfoAdapter.notifyDataSetChanged();
                mTvTime.setVisibility(View.GONE);
                handler1.sendEmptyMessage(0002);
                if (mIsRecording) {
                    if (mAVIStreamer != null) {
                        mAVIStreamer.stopRecording();
                    }
                    mIsRecording = false;
                    mScalePanel.setCanZoomOrDrag(true);

                    stopFlick(mTvRecordFlag);

                }
                break;
            case 3://正在连接
                break;
            case 4://已连接
                break;
        }
    }

    /**
     * 监听前后摄像头状态
     * @param is_online
     */
    @Override
    public void onRealCameraState(boolean is_online) {
        if(is_online){
            mImRealCamera.setVisibility(View.VISIBLE);
        }else{
            mImRealCamera.setVisibility(View.GONE);
            if(mAVPlayReal){
                mAVPlayReal = false;
                if(mIsRTSPPlayer){
                    //直播模式
                    mSwitchRealing = true;
                    //先关闭前视流，再启动后视流
                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_CLOSE, ARGS_RT_STREAM_CLOSE);
                }else{
                    if (mScalePanel.getLock()) {
                        showToast(getString(R.string.index_wait_hf));
                        return;
                    }
                    //回到直播
                    mScalePanel.setLock(true);
                    destroyBackPlayer();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mIsRTSPPlayer = true;
                            mGetThumbnail = false;
                            createRTSPPlayer();
                            displayPlayBackView_gone();
                            mImPlay.setVisibility(View.INVISIBLE);
                            mHandler.post(RTSPRunnable);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (mIsDevice_record) {
                                        mIsDevice_record = false;
                                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_START_RECORD, ARGS_START_RECORD);
                                    }
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mScalePanel.setLock(false);
                                        }
                                    }, 1500);
                                }
                            }, 200);
                        }
                    }, 300);
                }
            }
        }
    }

    private void createRTSPPlayer() {
        mAVPlayer_RTSP = new AVPlayer();
        boolean isSuccess = mAVPlayer_RTSP.createSocket(ICommon.AP_RT_STREAM_PORT, -1, "", AVPlayer.TYPE_RT_VIDEO);
        if (isSuccess) {
            mAVPlayer_RTSP.setQueueMax(1, 30, 256);
            try {
                mAVPlayer_RTSP.startListening();
            } catch (AVPlayerException e) {
                Dbug.e(tag, "Start Process fail");
                e.printStackTrace();
            }
            Dbug.i(tag, "Create socket success");
        } else {
            Dbug.e(tag, "Create socket fail");
        }
        syncDeviceStatus();
    }

    private void destroyRTSPPlayer() {
        if (mAVPlayer_RTSP != null) {
            try {
                mAVPlayer_RTSP.destroy();
            } catch (AVPlayerException e) {
                e.printStackTrace();
            }
            mAVPlayer_RTSP = null;
        }
    }

    private void createBackPlayer() {
        mAVPlayer_back = new StreamPlayer();
        Dbug.d(tag, "createBackPlayer");
        if (mAVPlayer_back != null) {
            int port;
            switch (mAVPlayer_back.getPlaybackMode()){
                case PLAYBACK_MODE_FRONT:
                    port = AP_VIDEO_PORT;
                    break;
                case PLAYBACK_MODE_REAR:
                    port = AP_REAR_PLAYBACK_RTS_PORT;
                    break;
                case PLAYBACK_MODE_NOT_READY:
                default:
                    Dbug.e(tag, "playback mode not ready...");
                    return;
            }
            String deviceip= AP_MODE_DEVICE_IP;
            if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                deviceip = ((MainActivity)(this.getActivity())).device_ip;
            if (mAVPlayer_back.connect(-1, deviceip, port)) {
                Dbug.i(tag, "Connected success=");
            } else {
                Dbug.e(tag, "Connected failure=");
            }
            mAVPlayer_back.setOnPlaybackListener(onFrameReceivedListener);
            mAVPlayer_back.setOnPlayStateListener(this);
            mAVPlayer_back.setOnConnectionListener(this);
            mAVPlayer_back.setOnBufferListener(this);
            mAVPlayer_back.setOnDownloadListener(this);
        }

    }

    private void destroyBackPlayer() {
        if (mAVPlayer_back != null) {
            if (isPlaying)
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_STOP, ARGS_VIDEO_STOP);
            mHandler.removeCallbacks(secondRunnable);
            try {
                Dbug.d(tag, "destroyBackPlayer");
                //mAVPlayer_back.setOnPlaybackListener(null);
                if (mAVPlayer_back != null) {
                    mAVPlayer_back.setOnConnectionListener(null);
                    mAVPlayer_back.setOnPlayStateListener(null);
                    mAVPlayer_back.setOnPlaybackListener(null);
                    onStateChanged(StreamPlayer.PlayState.STOP);
                    Dbug.i(tag, "onStop :disconnect 333=");
                    mIsPlayBackConnected = false;
                    mAVPlayer_back.disconnect();
                    mAVPlayer_back.release();
                    mAVPlayer_back = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                Dbug.d(tag, "destroyBackPlayer------Exception");
            }
            mAVPlayer_back = null;
        }
        isBrowseMode = false;
        isStopped = true;
        isPlaying = false;
        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_EXIT_BROWSING_MODE, ARGS_EXIT_BROWSING_MODE);
    }


    private void startEncodeAVIToMP4Service() {
        this.getActivity().startService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));
    }

    private void initAVIStream() {
        if (mAVIStreamer != null)
            return;
        mAVIStreamer = new AVIStreamer();
        mAVIStreamer.configureAudio(8000, 16, 1);
        mAVIStreamer.configureVideo(30, 640, 360);
        //mAVIStreamer.setDuration(20 * 60);
        mAVIStreamer.setOnRecordListener(new OnRecordListener() {
            @Override
            public void onStart(String filePath) {
                Dbug.w(tag, "onStart filePath:" + filePath);
            }

            @Override
            public void onCompletion(String filePath, boolean isSuccess, boolean isContinue) {
                if (isSuccess == false)
                    return;
                if (mIsExitDownload) {
                    mIsExitDownload = false;
                    return;
                }
                final String filepath_final = filePath;
                mIsEncording = true;
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        FileUtil.renameFile(filepath_final, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/", mTarget_PathName + ".avi");
                        EncodeAVIToMP4Service.addEncodeAVI(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".avi");
                        startEncodeAVIToMP4Service();
                        FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp/" + mTarget_PathName + ".JPG",
                                Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video");
                        VDO_SUCESS_PATH = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".avi";
                        mIsEncording = false;
                        // handler1.sendEmptyMessage(1113);
                    }
                }).start();
            }

            @Override
            public void onError(int state, String messages) {
                if (state == AVIStreamer.RecordError.ERROR_OUT_OF_STORAGE_SPACE) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            showToastLong(R.string.phone_space_inefficient);
                            stopRecording();
                        }
                    });
                }
            }

            /*
            @Override
            public void onCompletion(String filePath, boolean isSuccess) {
                if (isSuccess == false)
                    return;
                if (mIsExitDownload) {
                    mIsExitDownload = false;
                    return;
                }
                final String filepath_final = filePath;
                mIsEncording = true;
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        FileUtil.renameFile(filepath_final, Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/", mTarget_PathName + ".avi");
                        //EncodeAVIToMP4Service.getInstance().addEncodeAVI(Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/" + mTarget_PathName + ".avi");
                        //EncodeAVIToMP4Service.getInstance().startEncode();
                        FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/temp/" + mTarget_PathName + ".JPG",
                                Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video");
                        VDO_SUCESS_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/" + mTarget_PathName + ".avi";
                        mIsEncording = false;
                        // handler1.sendEmptyMessage(1113);
                    }
                }).start();
            }
            */

            /*
            @Override
            public void onStop(String filePath) {
                Dbug.e(tag, "onStop filePath:" + filePath);
                //mRecordList.add(filePath);
                //if (mIsEncording == false)
                //encording2Mp4();
                final String filepath_final = filePath;
                mIsEncording = true;
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        FileUtil.renameFile(filepath_final, Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/", mTarget_PathName + ".avi");
                        FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/temp/" + mTarget_PathName + ".JPG",
                                Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video");
                        VDO_SUCESS_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/" + mTarget_PathName + ".JPG";
                        mIsEncording = false;
                        handler1.sendEmptyMessage(1113);
                    }
                }).start();


            }
            */
        });
    }

    private void releaseAVIStream() {
        if (mAVIStreamer != null) {
            mAVIStreamer.stopRecording();
            mAVIStreamer.setOnRecordListener(null);
            mAVIStreamer.release();
        }
    }

    private int mEncordingIndex = 0;

    private void encording2Mp4() {
        //开始转码工作
        mIsEncording = true;
        //mHandler.postDelayed(encordingRunnable, 1500);
    }

    private boolean AVI2Mp4(int index) {
        boolean flag = true;
        if (mRecordList.size() < (index + 1))
            return flag;
        String path = mRecordList.get(index);
        int a = path.lastIndexOf(".");
        String cmdline = "ffmpeg -i " + path
                + " -s 568*320 " + path.substring(0, a) + ".mp4";
        final String[] argv = cmdline.split(" ");
        final Integer argc = argv.length;
        try {
            //if (com.leixiaohua1020.sffmpegandroidtranscoder.MainActivity.ffmpegcore(argc, argv) < 0) {
            //    Dbug.i("-----AVI2Mp4---", "encord,error!!!");
            // }
            mEncordingIndex++;
            flag = AVI2Mp4(mEncordingIndex);
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    private final Runnable encordingRunnable = new Runnable() {
        @Override
        public void run() {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (AVI2Mp4(mEncordingIndex) == false) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                showToast(getString(R.string.index_err_zm));
                            }
                        });
                        deleteTempAllFile(new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp"));
                        mRecordList.clear();
                        mIsEncording = false;
                        mEncordingIndex = 0;
                    } else {
                        if (mIsRecording) {
                            mHandler.postDelayed(encordingRunnable, 5000);
                        } else {
                            if (mRecordList.size() > 1) {
                                //合并mp4
                                //combineMp4(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".mp4");
                            } else {
                                FileUtil.renameFile(mRecordList.get(0),
                                        Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video", mTarget_PathName + ".mp4");
                            }

                            FileUtil.moveFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp/" + mTarget_PathName + ".JPG",
                                    Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video");
                            deleteTempAllFile(new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp"));
                            mRecordList.clear();
                            mIsEncording = false;
                            mEncordingIndex = 0;
                            // VDO_SUCESS_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/video/" + mTarget_PathName + ".JPG";
                            //handler1.sendEmptyMessage(1113);
                        }
                    }
                }
            }).start();


        }
    };

    private void deleteTempAllFile(File file) {
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                return;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
        }
    }

    private void combineMp4(String target_path) {
        //合并
        /*
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < mRecordList.size(); i++) {
            String path = mRecordList.get(i);
            int a = path.lastIndexOf(".");
            list.add(path.substring(0, a) + ".mp4");
        }
        try {
            VideoUtil.appendVideo(list, target_path);
        } catch (IOException e) {
            e.printStackTrace();
            Dbug.e("----combineMp4--", "----combineMp4 error----");
        }
        */

    }

    final SelectUpdataDialog.mOnSelVdeListener mOnSelectListener = new SelectUpdataDialog.mOnSelVdeListener() {

        @Override
        public void OnSel(final long start_time, final long stop_time) {
            Dbug.i(tag, "--111-----start_time:" + TimeFormater.formatYMDHMS(start_time) + "----stop_time:" + TimeFormater.formatYMDHMS(stop_time));
            showUpdateWindow(start_time, stop_time);
            Dbug.i(tag, "---222----start_time:" + TimeFormater.formatYMDHMS(start_time) + "----stop_time:" + TimeFormater.formatYMDHMS(stop_time));
            tryToStartRecord(start_time, stop_time);
            Dbug.i(tag, "----3333---start_time:" + TimeFormater.formatYMDHMS(start_time) + "----stop_time:" + TimeFormater.formatYMDHMS(stop_time));
        }

        @Override
        public void onCancle() {
            //mIsPlayBackConnected = false;
            //mAVPlayer_back.disconnect();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.index_im_2x:
                //快进
                switch (mFastForward) {
                    case 0:
                        //原速变为2x快进
                        mFastForward = 1;
                        mImSpeed.setImageResource(R.mipmap.icon_quickly_2x);
                        break;
                    case 1:
                        //2x快进变为4x快进
                        mFastForward = 2;
                        mImSpeed.setImageResource(R.mipmap.icon_quickly_4x);
                        break;
                    case 2:
                        //4x快进变为8x快进
                        mFastForward = 3;
                        mImSpeed.setImageResource(R.mipmap.icon_quickly_8x);
                        break;
                    case 3:
                        //8x快进变为原速播放
                        mFastForward = 0;
                        mImSpeed.setImageResource(R.mipmap.icon_quickly_1x);
                        break;
                }
                if(mAVPlayReal){
                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_VIDEO_PLAYBACK_SPEED, mFastForward + "");
                }else{
                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_PLAYBACK_SPEED, mFastForward + "");
                }
                break;
            case R.id.index_im_play_rl:
                if (mIsRTSPPlayer)
                    return;
                if (mScalePanel.getLock()) {
                    showToast(getString(R.string.index_wait_hf));
                    return;
                }
                if (!mIsPlayBackConnected) {
                    showToast(getString(R.string.index_hf_err));
                    return;
                }
                if (mAVPlayer_back != null && mAVPlayer_back.isPlaying()) {
                    mAVPlayer_back.pause();
                    mImPlay.setVisibility(View.VISIBLE);
                } else {
                    if (mGetThumbnail) {
                        showToast(getString(R.string.index_hc));
                        return;
                    }
                    if (mIsPlayBackConnected && !mGetThumbnail) {
                        if (mAVPlayer_back != null && mAVPlayer_back.isPaused()) {
                            mAVPlayer_back.play();
                            mImPlay.setVisibility(View.INVISIBLE);
                        } else {
                            if (mCurrVideoInfo != null) {
                                tryToStartPlayback();
                                mImPlay.setVisibility(View.INVISIBLE);
                            } else {
                                Dbug.w(tag, "The video not exist in selected position.");
                                showToast(getString(R.string.index_no_video));
                                isSeek = false;
                            }

                        }
                    }
                }

                break;
            case R.id.container1:
                if (mIsRTSPPlayer)
                    return;
                if (mScalePanel.getLock()) {
                    showToast(getString(R.string.index_wait_hf));
                    return;
                }
                if (!mIsPlayBackConnected) {
                    showToast(getString(R.string.index_hf_err));
                    return;
                }
                if (mAVPlayer_back != null && mAVPlayer_back.isPlaying()) {
                    mAVPlayer_back.pause();
                    mImPlay.setVisibility(View.VISIBLE);
                } else {
                    //回到播放状态
                    /*
                    if (mGetThumbnail) {
                        showToast("缓冲中，请稍后重试！");
                        return;
                    }
                    if (mIsPlayBackConnected && !mGetThumbnail) {
                        if (mAVPlayer_back != null && mAVPlayer_back.isPaused()) {
                            mAVPlayer_back.play();
                            mImPlay.setVisibility(View.INVISIBLE);
                        } else {
                            if (mCurrVideoInfo != null) {
                                tryToStartPlayback();
                                mImPlay.setVisibility(View.INVISIBLE);
                            } else {
                                Dbug.w(tag, "The video not exist in selected position.");
                                showToast("在该位置没有视频");
                                isSeek = false;
                            }

                        }
                    }
                    */
                }


                //mAVPlayer_back.disconnect();
                break;
            case R.id.index_im_new_play:
                if (mScalePanel.getLock()) {
                    showToast(getString(R.string.index_wait_hf));
                    return;
                }
                //回到直播
                mScalePanel.setLock(true);
                destroyBackPlayer();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIsRTSPPlayer = true;
                        mGetThumbnail = false;
                        createRTSPPlayer();
                        displayPlayBackView_gone();
                        mImPlay.setVisibility(View.INVISIBLE);
                        mHandler.post(RTSPRunnable);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (mIsDevice_record) {
                                    mIsDevice_record = false;
                                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_START_RECORD, ARGS_START_RECORD);
                                }
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mScalePanel.setLock(false);
                                    }
                                }, 1500);
                            }
                        }, 200);
                    }
                }, 300);
                break;
            case R.id.index_im_load:
                //弹出剪贴框
                if (mScalePanel.getLock()) {
                    showToast(getString(R.string.index_wait_hf));
                    return;
                }
                if (!mIsPlayBackConnected) {
                    showToast(getString(R.string.index_hf_err));
                    return;
                }
                if (mGetThumbnail) {
                    showToast(getString(R.string.index_hc));
                    return;
                }
                mIsCliked_download = true;
                bitmapInfoList.clear();
                //if (isPlaying == false || isStopped == true) {
                //    showToast("未开始回放视频！");
                //    return;
                // }
                if (null == mAVPlayer_back) {
                    showToast(getString(R.string.index_get_video));
                    return;
                }
                long time;
                if (mAVPlayer_back.isPlaying()) {
                    time = mAVPlayer_back.getCurrentPosition();
                    mAVPlayer_back.pause();
                } else {
                    time = mScalePanel.getCurrentTime();
                }
                mCurrVideoInfo = mVideoManager.getSelectedPosition(time);
                mImPlay.setVisibility(View.VISIBLE);

                if (mCurrVideoInfo == null) {
                    showToast(getString(R.string.index_no_video));
                } else {
                    selectUpdataDialog = SelectUpdataDialog.newInstance();
                    selectUpdataDialog.setOnEndListener(mOnSelectListener);
                    selectUpdataDialog.show(getActivity().getFragmentManager(), "SelectUpdataDialog");

                    tryToGetVideoThumbnail(time);
                }

                break;
            case R.id.index_im_photo:
                if (mImPlay.getVisibility() == View.VISIBLE) {
                    final byte[] photobtte = mSurfaceView.getBitmapData();
                    if (photobtte != null && photobtte.length > 0) {
                        mHandler.post(new Runnable() {

                            @Override
                            public void run() {
                                byte2Image(photobtte, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
                                handler1.sendEmptyMessage(1111);
                            }
                        });
                    } else {
                        showToast(getString(R.string.index_no_date));
                    }


                } else {
                    INDEX_TYPE = 1;
                    photoOpen();
                }

                //照相
                break;
            case R.id.index_im_full_screen:
                //全屏
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    toVertical();
                } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

                    if (mImPlay.isShown()) {
                        mIsUpdateSurfaceView = true;
                    } else {
                        mIsUpdateSurfaceView = false;
                    }

                    toHorizontal();
                }

                break;
            case R.id.index_im_realcamera:
                if(mSwitchRealing)
                    return;
                if(mApplication.getRealCamera()){
                    if(mIsRTSPPlayer){
                        //直播模式
                        mSwitchRealing = true;
                        mScalePanel.setLock(true);
                        if(mAVPlayer_RTSP.isFrontStreamPlaying()){
                            //先关闭前视流，再启动后视流
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_CLOSE, ARGS_RT_STREAM_CLOSE);
                        }else if(mAVPlayer_RTSP.isRearStreamPlaying()){
                            //先关闭后视流，再启动前视流
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_RTS_CLOSE, ARGS_REAR_RTS_CLOSE);
                        }
                    }else{
                        //回放模式
                        switch(mAVPlayer_back.getPlaybackMode()){
                            case PLAYBACK_MODE_NOT_READY://为准备状态
                                showToast(getString(R.string.index_wait_hf));
                                break;
                            case PLAYBACK_MODE_FRONT://前视模式
                                //mSwitchRealing = true;
                                //回放模式状态下的前后模式切换，从前视切换到后视
                                break;
                            case PLAYBACK_MODE_REAR://后视模式
                                //mSwitchRealing = true;
                                //回放模式状态下的前后模式切换，从从后视切换到前视
                                break;
                        }
                    }
                }
                break;

            case R.id.index_tv_error_video:
                //重新加载
                if (!mApplication.isSdcardState()) {
                    showToastLong(getString(R.string.index_no_sdvideo));
                    return;
                }
                mList.clear();
                isSOSVisible = true;
                mLlErrorSOS.setVisibility(View.GONE);
                mLlLoadSOS.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
                mLlNoVideo.setVisibility(View.GONE);
                mRlSOS.setVisibility(View.GONE);

                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                        if(mAVPlayReal){
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                        }else{
                            ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                        }
                    }
                }, 200);
                handler1.removeMessages(2222);
                handler1.sendEmptyMessageDelayed(2222, 15000);
                break;


            case R.id.index_rl_win_btn:
                if(android.os.Build.VERSION.SDK_INT > 23){
                    if(isOpenGPS(this.getActivity().getApplicationContext())){
                        if (this.getActivity() instanceof MainActivity) {
                            ((MainActivity) (this.getActivity())).searchWiFi();
                        }
                        if (mLlErrorSOS.getVisibility() == View.VISIBLE)
                            mLlErrorSOS.setVisibility(View.GONE);
                    }else{
                        //请打开GPS进行扫描附近WiFi
                        this.showToast(getString(R.string.open_gps));
                    }
                }else{
                    if (this.getActivity() instanceof MainActivity) {
                        ((MainActivity) (this.getActivity())).searchWiFi();
                    }
                    if (mLlErrorSOS.getVisibility() == View.VISIBLE)
                        mLlErrorSOS.setVisibility(View.GONE);
                }

                break;
            case R.id.index_btn_pho_sucess:
                if (INDEX_TYPE == 1) {
                    //跳转到相册界面
                    Intent intent = new Intent(getActivity().getApplicationContext(), PhotoActivity.class);
                    if (null != PHO_SUCESS_PATH) {
                        //intent.putExtra("photo_file", Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/photo/" + PHO_SUCESS_PATH);
                        intent.putExtra("photo_file", "0");
                        getActivity().startActivity(intent);

                    }
                } else if (INDEX_TYPE == 2) {
                    //跳转到录像界面
                    // Intent intent2 = new Intent(getActivity().getApplicationContext(), VideoPlayerActivity.class);
                    //if (null != VDO_SUCESS_PATH) {
                    //intent.putExtra("video_file", allDataInfoList.get(position).getPath());
                    //intent2.putExtra("video_file", "0");
                    //getActivity().startActivityForResult(intent, 1000);
                    // getActivity().startActivity(intent2);

                    // }
                }

                break;
            case R.id.index_im_cancle_pho_sucess:
                //隐藏
                mRlPhoSucess.setVisibility(View.GONE);
                break;

            case R.id.index_im_disable_wifi:
                ((MainActivity)(this.getActivity())).disconnectDevice_self();
                break;

        }
    }


    private void createTempFile() {
        String avitomp4_path = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/avi2mp4";
        File avitomp4_pathF = new File(avitomp4_path);
        if (avitomp4_pathF.exists() == false)
            avitomp4_pathF.mkdirs();

        String mp4_path = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/mp4";
        File mp4_pathF = new File(mp4_path);
        if (mp4_pathF.exists() == false)
            mp4_pathF.mkdirs();

        String temp = Environment.getExternalStorageDirectory().getPath() + "/" + "chainway/168cardev" + "/temp";
        File tempF = new File(temp);
        if (tempF.exists() == false)
            tempF.mkdirs();

        String video = Environment.getExternalStorageDirectory().getPath() + "/" + "chainway/168cardev" + "/video";
        File videoF = new File(video);
        if (videoF.exists() == false)
            videoF.mkdirs();

        String photo = Environment.getExternalStorageDirectory().getPath() + "/" + "chainway/168cardev" + "/photo";
        File photoF = new File(photo);
        if (photoF.exists() == false)
            photoF.mkdirs();
    }


    //拍照
    private void photoOpen() {
        //SavePictureUtil.saveScreen(mRlBackground, Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/download");
        mIsPhoto = true;
    }

    //切换到竖屏
    public void toVertical() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    //切换到横屏
    private void toHorizontal() {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }


    private void shootSound() {
        int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
//        volume = mAudioManager.getStreamVolume( AudioManager.STREAM_ALARM);

        if (volume != 0) {
            if (mMediaPlayer == null) {
                mMediaPlayer = MediaPlayer.create(getActivity(), (R.raw.camera_click));
            }
            if (mMediaPlayer != null) {
                mMediaPlayer.start();
            }
        }
    }

    private void initFileDir() {
        if (mApplication == null || mApplication.getDeviceUUID() == null) {
            return;
        }
        String imagePath = Environment.getExternalStorageDirectory().getPath() + "/SportCamera/" + mApplication.getDeviceUUID() + "/image/";
        File imageFile = new File(imagePath);
        if (null != imageFile) {
            delete(imageFile);
        }
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/SportCamera/" + mApplication.getDeviceUUID() + "/video/";
        File file = new File(filePath);
        if (null != file) {
            delete(file);
        }
        String thumPath = Environment.getExternalStorageDirectory().getPath() + "/SportCamera/" + mApplication.getDeviceUUID() + "/thumb/";
        File thumbFile = new File(thumPath);
        if (null != thumbFile) {
            delete(thumbFile);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void startFlick(View view) {
        if (null == view) {
            return;
        }

        view.setVisibility(View.VISIBLE);
        Animation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(500);
        alphaAnimation.setInterpolator(new LinearInterpolator());
        alphaAnimation.setRepeatCount(Animation.INFINITE);
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        view.startAnimation(alphaAnimation);
    }

    private void stopFlick(View view) {

        if (null == view) {
            return;
        }
        INDEX_TYPE = 2;
        view.setVisibility(View.INVISIBLE);
        view.clearAnimation();
    }

    private void syncDeviceStatus() {

        //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE);
        if (mAVPlayer_RTSP != null) {
            tryToPlay();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getActivity() != null) {
            IntentFilter intentFilter = new IntentFilter(IAction.ACTION_SPECIAL_DATA);
            intentFilter.addAction(ACTION_DEVICE_CONNECTION_SUCCESS);
            intentFilter.addAction(ACTION_DEVICE_LANG_CHANGED);
            intentFilter.addAction(ACTION_GET_ALL_VIDEO_FILE_NAME);
            intentFilter.addAction(ACTION_GET_RECORDING_STATUS);
            intentFilter.addAction(ACTION_RELEASE_SOSSTORAGE_INFO);
            intentFilter.addAction(ACTION_RESPONDING_VIDEO_DESC_REQUEST);
            intentFilter.addAction(ACTION_GET_VERSION_INFO);
            intentFilter.addAction(ACTION_GET_DEVICE_INFO);
            intentFilter.addAction(IAction.ACTION_ENCORDING_SUCCESS);
            intentFilter.addAction(IAction.ACTION_ENCORDING_CURRENT_START);
            intentFilter.addAction(IAction.ACTION_ENCORDING_CURRENT_END);
            intentFilter.addAction(IAction.ACTION_REVERSING_STATE);
            getActivity().registerReceiver(mReceiver, intentFilter);
        }
    }


    @Override
    public void onStop() {
        Dbug.i("baseactivity---", "IndexFragment-onStop");
        super.onStop();
        mIsRecording = false;
        if (selectUpdataDialog != null && selectUpdataDialog.isShowing())
            selectUpdataDialog.dismiss();
        if (selectDownDialog != null && selectDownDialog.isShowing())
            selectDownDialog.dismiss();
        if (phoDialog != null && phoDialog.isShowing())
            phoDialog.dismiss();
        isSeek = false;
        if (mAVPlayer_RTSP != null) {
            tryToStop();
            mHandler.removeCallbacks(RTSPRunnable);
        }
        if (getActivity() != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
        mIsPlayBackConnected = false;
    }

    @Override
    public void onPause() {
        super.onPause();
        mAVPlayReal = false;
        mSwitchRealing = false;
        Dbug.i(tag, "----onPause:" + "-------");
        if (mIsRTSPPlayer == false) {
            mIsRecording = false;
            //mImPlay.setVisibility(View.GONE);
            if (mAVIStreamer != null && mAVIStreamer.isRecording()) {
                if (mAVIStreamer != null) {
                    Dbug.i(tag, "----onPause:" + "true");
                    //mAVIStreamer.stopRecording();
                    mAVIStreamer.stopRecording();
                    mAVIStreamer.setOnRecordListener(null);
                    mAVIStreamer.release();
                    mAVIStreamer = null;
                }
            } else {
                Dbug.i(tag, "onPause stop recording=");
            }
            mIsRTSPPlayer = true;
            displayPlayBackView_gone();
            destroyBackPlayer();
            mImPlay.setVisibility(View.INVISIBLE);
            createRTSPPlayer();
            mHandler.post(RTSPRunnable);
            if (mIsDevice_record) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_START_RECORD, ARGS_START_RECORD);
                    }
                }, 200);
                mIsDevice_record = false;
            }
            // mScalePanel.setVisibility(View.GONE);
            // mZhiBo_Seek.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mApplication.getIsOffLineMode()) {
            tryToStop();
            destroyRTSPPlayer();
            destroyBackPlayer();
            mSurfaceView.setVisibility(View.GONE);
            mRl_Start.setVisibility(View.VISIBLE);
            mImwin.setVisibility(View.VISIBLE);
            mIsDevice_Recording = false;
            mHandler.removeCallbacks(RedPointRunnable);

            index_redpoint.setVisibility(View.GONE);
            // mScalePanel.setVisibility(View.GONE);
            // mZhiBo_Seek.setVisibility(View.VISIBLE);
            mList.clear();
            mSosInfoAdapter.notifyDataSetChanged();
        } else {

            /**Get timer picture status when fragment first created*/
            //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_TIMER_PICTURE_STATUS);
            if (MainActivity.CLEAN_SOS) {
                mList.clear();
                mSosInfoAdapter.notifyDataSetChanged();
                mListView.setVisibility(View.GONE);
                mLlNoVideo.setVisibility(View.VISIBLE);
                mRlSOS.setVisibility(View.GONE);
                mIsGetSOS = false;
                if(mAVPlayReal){
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                }else{
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                }
                MainActivity.CLEAN_SOS = false;
            } else if (MainActivity.CLEAN_ALL) {
                mList.clear();
                mScalePanel.SetCalStuff(null);
                mSosInfoAdapter.notifyDataSetChanged();
                mListView.setVisibility(View.GONE);
                mLlNoVideo.setVisibility(View.VISIBLE);
                mRlSOS.setVisibility(View.GONE);
                mIsGetSOS = false;
                if(mAVPlayReal){
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                }else{
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                }
                MainActivity.CLEAN_ALL = false;
            }


            syncDeviceStatus();
        }
        if (mBitmapCache == null) {
            mBitmapCache = BitmapCache.getInstance();
        }
    }

    @Override
    public void onDestroy() {
        if (mBitmapCache != null) {
            mBitmapCache.clearCache();
            mBitmapCache = null;
        }

        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
        }

        if (null != wake_lock && wake_lock.isHeld()) {
            wake_lock.release();
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
        }
        Dbug.e(tag, "----------------onDestroy :");
        releaseAVIStream();
        destroyRTSPPlayer();
        destroyBackPlayer();
        Dbug.e(tag, "----------------onDestroy :");
        isStopped = true;
        isPlaying = false;
        mIsRTSPPlayer = true;
        super.onDestroy();
    }

    private void delete(File f) {
        ((MainActivity) (this.getActivity())).delete(f);
    }


    private void setAspectRatio() {
        Display display = getActivity().getWindowManager().getDefaultDisplay();

        // display size in pixels
        Point size = new Point();
        display.getSize(size);

        Dbug.i(tag, "surfaceView_Width=" + size.x + ", surfaceView_Height=" + size.y);

        float DEFAULT_VIDEO_WIDTH = 1280;
        float ratio_width = size.x / DEFAULT_VIDEO_WIDTH;
        float DEFAULT_VIDEO_HEIGHT = 720;
        float ratio_height = size.y / DEFAULT_VIDEO_HEIGHT;
        float aspectRatio = DEFAULT_VIDEO_WIDTH / DEFAULT_VIDEO_HEIGHT;

        ViewGroup.LayoutParams layoutParams = mSurfaceView.getLayoutParams();

        if (ratio_width > ratio_height) {
            layoutParams.width = (int) (size.y * aspectRatio);
            layoutParams.height = size.y;
        } else {
            layoutParams.width = size.x;
            layoutParams.height = (int) (size.x / aspectRatio);
        }

        Dbug.i(tag, "layoutParams.width=" + layoutParams.width + ", layoutParams.height=" + layoutParams.height);
        //mSurfaceView.setLayoutParams(layoutParams);
        //mSurfaceView.invalidate();
        //mSurfaceView.setWidthAndHeight(layoutParams.width, layoutParams.height);
        mSurfaceView.setLayoutParams(layoutParams);

    }

    /**
     * 直播状态下监听
     */
    private final OnRTStreamListener onRTStreamListener = new OnRTStreamListener() {
        /*
        @Override
        public void onVideo(byte[] videoData) {
                   Dbug.d(tag, "OnRTStreamListener : onVideo=" + videoData.length);
            mSurfaceView.drawBitmap(videoData, true);
            if (mIsPhoto) {
                mIsPhoto = false;
                final byte[] photeData1 = videoData;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(photeData1, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
                        handler1.sendEmptyMessage(1111);
                    }
                });

            }

            if (mIsCutRecordImage) {
                mIsCutRecordImage = false;
                final byte[] video = videoData;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(video, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp", mTarget_PathName + ".JPG");
                    }
                });
            }
            if (mIsRecording)
                mAVIStreamer.addData(AVIStreamer.TYPE_AVI_VIDEO, videoData, videoData.length);
        }
        */

        @Override
        public void onVideo(byte[] videoData, int resolutionType,int rtsChannel) {
            mSurfaceView.drawBitmap(videoData, true);
            if (mIsPhoto) {
                mIsPhoto = false;
                final byte[] photeData1 = videoData;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(photeData1, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
                        handler1.sendEmptyMessage(1111);
                    }
                });

            }

            if (mIsCutRecordImage) {
                mIsCutRecordImage = false;
                final byte[] video = videoData;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(video, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp", mTarget_PathName + ".JPG");
                    }
                });
            }
            if (mIsRecording)
                mAVIStreamer.addData(AVIStreamer.TYPE_AVI_VIDEO, videoData, videoData.length);
        }

        @Override
        public void onAudio(byte[] audioData) {
            if (mMute == false)
                mSurfaceView.writeAudioData(audioData);
            if (mIsRecording)
                mAVIStreamer.addData(AVIStreamer.TYPE_AVI_AUDIO, audioData, audioData.length);
        }

        @Override
        public void onPhoto(byte[] photoData) {
//            Dbug.w(tag, "OnRTStreamListener : onPhoto=" + photoData.length);
            mSurfaceView.clearCanvas();
            mSurfaceView.drawBitmap(photoData, true);
        }
    };

    //byte数组到图片
    public void byte2Image(byte[] data, String root_path) {
        if (data.length < 3 || root_path.equals("")) return;
        File rootDir = new File(root_path + "/");
        if (!rootDir.exists()) {
            rootDir.mkdirs();
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        if (bitmap != null) {
            try {
                PHO_SUCESS_PATH = "JPG_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1) + ".JPG";
                //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(rootDir, "JPG_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1) + ".JPG")));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(rootDir, PHO_SUCESS_PATH)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                bitmap = null;
            }
        }


    }

    //byte数组到图片
    public void byte2Image(byte[] data, String root_path, String imagename) {
        if (data.length < 3 || root_path.equals("")) return;
        File rootDir = new File(root_path + "/");
        if (!rootDir.exists()) {
            rootDir.mkdirs();
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        if (bitmap != null) {
            try {
                //PHO_SUCESS_PATH = "JPG_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1) + ".JPG";
                //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(rootDir, "JPG_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1) + ".JPG")));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(rootDir, imagename)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                bitmap = null;
            }
        }


    }

    private void tryToPlay() {
        if (mAVPlayer_RTSP != null) {
            //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE);
            if(mAVPlayReal){
                Dbug.i(tag, "tryToPlay: CMD_REAR_RTS_OPEN=" + CMD_REAR_RTS_OPEN);
                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_RTS_OPEN);
            }else{
                Dbug.i(tag, "tryToPlay: CMD_RT_STREAM_OPEN=" + CMD_RT_STREAM_OPEN);
                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_RT_STREAM_OPEN);
            }
            if(mApplication.getRealCamera()){
                mImRealCamera.setVisibility(View.VISIBLE);
            }else{
                mImRealCamera.setVisibility(View.GONE);
            }
            mHandler.removeCallbacks(RTSPRunnable);
            mHandler.post(RTSPRunnable);
        }
    }

    private void tryToStop() {
        if (mAVPlayer_RTSP != null) {
            if(mAVPlayReal){
                Dbug.i(tag, "tryToStop: CMD_REAR_RTS_CLOSE=" + CMD_REAR_RTS_CLOSE);
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_RTS_CLOSE, ARGS_REAR_RTS_CLOSE);
            }else{
                Dbug.i(tag, "tryToStop: CMD_RT_STREAM_CLOSE=" + CMD_RT_STREAM_CLOSE);
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_RT_STREAM_CLOSE, ARGS_RT_STREAM_CLOSE);
            }

        }
    }

    /**
     * 时间轴动作监听
     */
    private final TLView.OnValueChangeListener onValueChangeListener = new TLView.OnValueChangeListener() {
        @Override
        public void onValueChangeEnd(final Calendar calendar) {
            if ((System.currentTimeMillis() - calendar.getTimeInMillis()) <= 3 * 1000)
                return;

            if (mGetThumbnail)
                return;
            if (mIsRTSPPlayer == true) {
                //if (mIsDevice_Recording)
                //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                mIsRTSPPlayer = false;
                mScalePanel.setLock(true);
                tryToStop();
                destroyRTSPPlayer();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mImPlay.setVisibility(View.VISIBLE);
                        mTvTime.setText(getString(R.string.index_hf));
                    }
                });
                String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                Dbug.d(tag, "recordState:" + recordState);
                if (ARGS_IN_RECORDING.equals(recordState)) {
                    mFirstTime = calendar.getTimeInMillis();
                    mIsFirstPlayBackConnected = true;
                    mIsDevice_record = true;
                    ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                    /*
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (!isBrowseMode) {
                                CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mIsFirstPlayBackConnected = true;

                                        createBackPlayer();
                                        mHandler.removeCallbacks(RTSPRunnable);
                                        mScalePanel.setLock(false);

                                    }
                                }, 500);

                            }
                        }
                    }, 600);
                    */
                } else {
                    if (!isBrowseMode) {
                        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                                mIsFirstPlayBackConnected = true;
                                mFirstTime = calendar.getTimeInMillis();
                                createBackPlayer();
                                mHandler.removeCallbacks(RTSPRunnable);
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        mScalePanel.setLock(false);
                                    }
                                }, 1000);

                            }
                        }, 2500);

                    }
                }
                displayPlayBackView_visiable();

            } else {
                displayValueInfo(calendar);
            }

        }


        @Override
        public void onMiddleTime(String dateStr, String timeStr) {
            if (null != dateStr && null != timeStr) {
                mTvPbTime.setText(timeStr);
                mTvPbData.setText(dateStr);
            }


        }

        @Override
        public void onArrivedRight() {
            mLlPlayBack.setVisibility(View.GONE);
            if (mIsRTSPPlayer == false) {
                mScalePanel.setLock(true);
                destroyBackPlayer();
                mIsRTSPPlayer = true;
                mGetThumbnail = false;
                createRTSPPlayer();
                mHandler.post(RTSPRunnable);
                displayPlayBackView_gone();
                mImPlay.setVisibility(View.INVISIBLE);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mIsDevice_record) {
                            mIsDevice_record = false;
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_START_RECORD, ARGS_START_RECORD);
                        }
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mScalePanel.setLock(false);
                            }
                        }, 1500);
                    }
                }, 200);
            }
        }

        @Override
        public void onArrivedLeft() {
            showToast(getString(R.string.index_fir_video));
        }

        @Override
        public void onTouchDown() {
            mLlPlayBack.setVisibility(View.VISIBLE);
        }

        @Override
        public void onTouchUp() {
            mLlPlayBack.setVisibility(View.GONE);
        }

        @Override
        public void onCannotMoving() {
            showToastLong(getString(R.string.index_update_video));
        }

        @Override
        public void onLock(boolean exist_Sdcard, boolean s, String info) {
            if (mApplication.getIsOffLineMode() == false) {
                //已经连接设备wifi
                if (!exist_Sdcard) {
                    showToastLong(getString(R.string.index_no_tf));
                } else {
                    showToastLong(getString(R.string.index_wait_hc));
                }

            } else {
                //没有连接设备wifi
                showToast(getString(R.string.please_connect));
            }
        }

    };


    private void displayValueInfo(Calendar calendar) {
        if (!mIsPlayBackConnected) {
            Dbug.e(tag, "onValueChangeEnd: disconnected!!");
            return;
        }
        mCurrVideoInfo = mVideoManager.getSelectedPosition(calendar.getTimeInMillis());
        if (mCurrVideoInfo == null) {
            //查找最近的历史视频
            mCurrVideoInfo = mScalePanel.getNearestVideoInfo(calendar.getTimeInMillis(), false);
        }
        Dbug.e(tag, "onValueChangeEnd:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()) + ", isPlaying=" + isPlaying);
        if (mAVPlayer_back != null && mAVPlayer_back.isPlaying()) {
            //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_STOP, ARGS_VIDEO_STOP);
            if (!isSeek) {
                isSeek = true;
                mIsPlayBackConnected = false;
                mAVPlayer_back.disconnect();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mImPlay.setVisibility(View.VISIBLE);
                    }
                });
                isPlaying = false;
                isStopped = true;
                if (mCurrVideoInfo == null) {
                    mSurfaceView.setBitmapData(null);
                }
                if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                    mGetThumbnail = true;
                    String deviceip= AP_MODE_DEVICE_IP;
                    if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                        deviceip = ((MainActivity)(this.getActivity())).device_ip;
                    if(mAVPlayReal){
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }else{
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }
                }
            }

        } else if (mAVPlayer_back != null && mAVPlayer_back.isPaused()) {
            mAVPlayer_back.play();
            if (!isSeek) {
                isSeek = true;
                mIsPlayBackConnected = false;
                mAVPlayer_back.disconnect();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mImPlay.setVisibility(View.VISIBLE);
                    }
                });
                isPlaying = false;
                isStopped = true;
                if (mCurrVideoInfo == null) {
                    mSurfaceView.setBitmapData(null);
                }
                if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                    mGetThumbnail = true;
                    String deviceip= AP_MODE_DEVICE_IP;
                    if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                        deviceip = ((MainActivity)(this.getActivity())).device_ip;
                    if(mAVPlayReal){
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }else{
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }
                }
            }
        } else {
            //mAVPlayer_back.disconnect();
            isPlaying = false;
            isStopped = true;
            //tryToStartPlayback();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mImPlay.setVisibility(View.VISIBLE);
                }
            });
            if (mCurrVideoInfo == null) {
                Dbug.w(tag, "The video not exist in selected position.");
                mSurfaceView.setBitmapData(null);
                showToast(getString(R.string.index_no_video));
                return;
            }
            Dbug.i(tag, "------tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()));
            if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                mGetThumbnail = true;
                String deviceip= AP_MODE_DEVICE_IP;
                if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                    deviceip = ((MainActivity)(this.getActivity())).device_ip;
                if(mAVPlayReal){
                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                }else{
                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                }
            }
            isPlaying = false;
            isStopped = true;
            /*
            if (mCurrVideoInfo == null) {
                //查找最近的历史视频
                mCurrVideoInfo = mScalePanel.getNearestVideoInfo(calendar.getTimeInMillis());
                if (mCurrVideoInfo != null) {
                    Dbug.w(tag, "tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()));
                    //mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
                }
            } else {
                Dbug.w(tag, "tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()));
                //mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
            }
            */
        }

        /*
        if (mCurrVideoInfo != null) {
            isRequestThumbnail = true;
            mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (isStopped) {
                        tryToStartPlayback();
                        // CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_START_PLAYBACK);
                        mAVPlayer_back.play();
                    } else {
                        if (isPlaying) {
                            //CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_PAUSE, ARGS_VIDEO_PAUSE);
                            isPlaying = false;
                        } else {
                            //CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_START_PLAYBACK);
                            isPlaying = true;
                        }
                    }
                }
            }, 2000);
        }
        */
    }

    private void displayValueInfo(long calendartime) {
        if (!mIsPlayBackConnected) {
            Dbug.e(tag, "onValueChangeEnd: disconnected!!");
            return;
        }
        mCurrVideoInfo = mVideoManager.getSelectedPosition(calendartime);
        if (mCurrVideoInfo == null) {
            //查找最近的历史视频
            mCurrVideoInfo = mScalePanel.getNearestVideoInfo(calendartime, false);
            if (mCurrVideoInfo != null) {
                Dbug.w(tag, "tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendartime));
            }
        }
        Dbug.e(tag, "onValueChangeEnd:" + yyyy_MMddHHmmss.format(calendartime) + ", isPlaying=" + isPlaying);
        if (mAVPlayer_back != null && mAVPlayer_back.isPlaying()) {
            //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_STOP, ARGS_VIDEO_STOP);
            if (!isSeek) {
                isSeek = true;
                mIsPlayBackConnected = false;
                mAVPlayer_back.disconnect();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mImPlay.setVisibility(View.VISIBLE);
                    }
                });
                isPlaying = false;
                isStopped = true;
                if (mCurrVideoInfo == null) {
                    mSurfaceView.setBitmapData(null);
                }
                if (mAVPlayer_back != null && mCurrVideoInfo != null){
                    String deviceip= AP_MODE_DEVICE_IP;
                    if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                        deviceip = ((MainActivity)(this.getActivity())).device_ip;
                    if(mAVPlayReal){
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }else{
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }
                }
            }
        } else {
            //mAVPlayer_back.disconnect();
            //tryToStartPlayback();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mImPlay.setVisibility(View.VISIBLE);
                }
            });
            if (mCurrVideoInfo == null) {
                Dbug.w(tag, "The video not exist in selected position.");
                showToast(getString(R.string.index_no_video));
                return;
            }
            if (mCurrVideoInfo == null) {
                mSurfaceView.setBitmapData(null);
            }
            if (mAVPlayer_back != null && mCurrVideoInfo != null){
                String deviceip= AP_MODE_DEVICE_IP;
                if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                    deviceip = ((MainActivity)(this.getActivity())).device_ip;
                if(mAVPlayReal){
                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                }else{
                    mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                }
            }
            isPlaying = false;
            isStopped = true;
            /*
            if (mCurrVideoInfo == null) {
                //查找最近的历史视频
                mCurrVideoInfo = mScalePanel.getNearestVideoInfo(calendar.getTimeInMillis());
                if (mCurrVideoInfo != null) {
                    Dbug.w(tag, "tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()));
                    //mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
                }
            } else {
                Dbug.w(tag, "tryToGetVideoThumbnail---:" + yyyy_MMddHHmmss.format(calendar.getTimeInMillis()));
                //mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
            }
            */
        }

        /*
        if (mCurrVideoInfo != null) {
            isRequestThumbnail = true;
            mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (isStopped) {
                        tryToStartPlayback();
                        // CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_START_PLAYBACK);
                        mAVPlayer_back.play();
                    } else {
                        if (isPlaying) {
                            //CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_PAUSE, ARGS_VIDEO_PAUSE);
                            isPlaying = false;
                        } else {
                            //CommandHub.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_START_PLAYBACK);
                            isPlaying = true;
                        }
                    }
                }
            }, 2000);
        }
        */
    }

    /**
     * 图像二进制流转换成bitmap
     * @param imgByte
     * @return
     */
    public static Bitmap byteToBitmap(byte[] imgByte) {
        InputStream input = null;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        //noinspection deprecation
        options.inPurgeable = true;
        input = new ByteArrayInputStream(imgByte);
        SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
                input, null, options));
        bitmap = (Bitmap) softRef.get();
        if (imgByte != null) {
            imgByte = null;
        }

        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 回放状态中的缩略图、视频图像监听
     */
    private OnPlaybackListener onFrameReceivedListener = new OnPlaybackListener() {
        @Override
        public void onThumbnail(byte[] thumbnail, long millisecond, boolean isFinished) {
            Dbug.e(tag, "onFrameReceived thumbnail isFinished=" + isFinished + ", isRequestThumbnail=" + isRequestThumbnail);
            if (mGetThumbnail)
                mSurfaceView.drawBitmap(thumbnail, true);
            if (thumbnail != null && thumbnail.length > 0) {

                try {
                    BitmapInfo bitmapinfo = new BitmapInfo();
                    Bitmap bitmap = byteToBitmap(thumbnail);
                    bitmapinfo.setmBitmap(bitmap);
                    bitmapinfo.setTime(millisecond);
                    Dbug.i(tag, "onFrameReceivedListener------millisecond:" + TimeFormater.formatYMDHMS(millisecond));
                    bitmapInfoList.add(bitmapinfo);
                } catch (Exception e) {
                    //内存不够
                }

            }

            if (isFinished) {
                mGetThumbnail = false;
                if (bitmapInfoList.size() > 2) {
                    isRequestThumbnail = false;
                    //这里标记完成缩略图加载，可以将bitmapInfoList中的数据加载出来
                    if (null != selectUpdataDialog && selectUpdataDialog.isShowing()) {
                        handler1.sendEmptyMessage(3333);

                    }
                }


            }
            /**若当前位置没有视频将不显示缩略图*/
            //mSurfaceView.drawBitmap(thumbnail, true);
            if (isRequestThumbnail) {
                isRequestThumbnail = false;
            }
        }

        @Override
        public void onAudio(final byte[] audio, boolean isPlayMode) {
            if (isPlayMode) {
                Dbug.w(tag, "onAudioReceived audioFrame=" + audio.length);
                if (mFastForward == 0)
                    mSurfaceView.writeAudioData(audio);
            } else {
                /**保存到手机本地*/
                if (mIsRecording)
                    mAVIStreamer.addData(AVIStreamer.TYPE_AVI_AUDIO, audio, audio.length);
            }

        }

        @Override
        public void onVideo(final byte[] video, boolean isPlayMode) {
//            Dbug.e(tag, "onVideoReceived=" + videoFrame.length);
            if (isPlayMode) {
                mSurfaceView.drawBitmap(video, true);
            } else {
                /**保存到手机本地*/
                if (mIsRecording)
                    mAVIStreamer.addData(AVIStreamer.TYPE_AVI_VIDEO, video, video.length);
            }
            if (mIsPhoto) {
                mIsPhoto = false;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(video, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo");
                        handler1.sendEmptyMessage(1111);
                    }
                });

            }
            if (mIsCutRecordImage) {
                mIsCutRecordImage = false;
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        byte2Image(video, Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp", mTarget_PathName + ".JPG");
                    }
                });
            }

        }

        @Override
        public void onPlayFile(String s) {

        }
    };

    //intranet ftp
    private static final String INSIDE_FTP_HOST_NAME = "192.168.1.1";
    private static final String INSIDE_FTP_USER_NAME = "FTPX";
    private static final String INSIDE_FTP_PASSWORD = "12345678";
    private final Runnable uploadFTPServer = new Runnable() {
        @Override
        public void run() {
            connectFTP(INSIDE_FTP_HOST_NAME, 21, INSIDE_FTP_USER_NAME, INSIDE_FTP_PASSWORD);
        }
    };

    private String workPath;

    /**
     * connect FTP
     */
    private void connectFTP(String add, int port, String name, String paw) {
        FTPClient mFTPClient = new FTPClient();
        mFTPClient.setControlEncoding("GBK");
        mFTPClient.setDefaultPort(port);
        try {
            mFTPClient.connect(add);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
            try {
                if (mFTPClient.login(name, paw)) {
                    String currentPath = mFTPClient.printWorkingDirectory();
                    currentPath = currentPath + workPath;
                    //Dbug.i(tag, "Change Working Directory to : " +currentPath );
                    if (!mFTPClient.changeWorkingDirectory(currentPath)) {
                        //Dbug.e(tag, "Change Working Directory to to : " +currentPath + " fail.");
                        try {
                            mFTPClient.disconnect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return;
                    }
                    byte[] videoMsg = ParseHelper.getInstance().getSortedVideo().getBytes();
                    //Dbug.d(tag, "videoMsg=========length=" + videoMsg.length);
                    ByteArrayInputStream bis = new ByteArrayInputStream(videoMsg);
                    mFTPClient.enterLocalPassiveMode();
                    mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                    mFTPClient.setBufferSize(1024 * 1024 * 5); //5M

                    if (mFTPClient.storeFile("vf_order.txt", bis)) {
                        //Dbug.d(tag, "upload file success!");
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                //设置时间块数据
                                mScalePanel.SetCalStuff(ParseHelper.getInstance().getSortedVideos());
                                if (mList.size() == 0) {
                                    List<VideoInfo> vf = ParseHelper.getInstance().getSortedVideos();
                                    mList.clear();
                                    for (int i = 0; i < vf.size(); i++) {
                                        if (vf.get(i).getIsLocked())
                                            mList.add(vf.get(i));
                                    }
                                    //mSosInfoAdapter.notifyDataSetChanged();
                                    showSOSList(mList.size());
                                    mIsGetSOS = false;
                                }
                            }
                        });
                    } else {
                        Dbug.e(tag, "upload file failed!");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (mFTPClient.isConnected()) {
                    try {
                        mFTPClient.disconnect();
                        //Dbug.d(tag, "FTPClient is disconnected success!");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            Dbug.w(tag, "Reply code is not a positive completion response.");
        }
    }

    /**
     * 进入回放某一个视频，发送命令
     */
    private synchronized void tryToStartPlayback() {
        if (mCurrVideoInfo == null) {
            Dbug.w(tag, "The video not exist in selected position.");
            showToast(getString(R.string.index_no_video));
            isSeek = false;
            return;
        }
        Dbug.w(tag, "tryToStartPlayback=" + yyyy_MMddHHmmss.format(mCurrVideoInfo.getStartTime().getTime()) + ", offset=" + mCurrVideoInfo.getTimeOffset());
        int index = ParseHelper.getInstance().getSelectVideoIndexInTxt(mCurrVideoInfo.getFilePath());
        if(mAVPlayReal){
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_VIDEO_PLAYBACK_START, mCurrVideoInfo.getFilePath(), mCurrVideoInfo.getTimeOffset() + "", ARGS_VIDEO_START_PLAYBACK, index + "");
        }else{
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_START_PLAYBACK, mCurrVideoInfo.getFilePath(), mCurrVideoInfo.getTimeOffset() + "", ARGS_VIDEO_START_PLAYBACK, index + "");
        }

    }


    /**
     * 回放状态下的时间轴移动监听
     */
    private final Runnable secondRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(secondRunnable, 1000);
            Dbug.e(tag, "lTime =" + "---postDelayed");
            if (mAVPlayer_back != null) {
                if (isPlaying) {
                    long lTime = mAVPlayer_back.getCurrentPosition();
                    String text = TimeFormater.dateLongFormatString(lTime, TimeFormater.format2, 2000);
                    //if (text != null)
                    //mTvTime.setText("回放|" + text);
                    mScalePanel.setTimeOffset(lTime);
                    Dbug.i(tag, "lTime =" + yyyy_MMddHHmmss.format(lTime));
                }

            }

        }
    };

    /**
     * 在直播状态下的时间走向，同时时间轴移动
     */
    private final Runnable RTSPRunnable = new Runnable() {
        @Override
        public void run() {
            if (mAVPlayer_RTSP != null && mIsRTSPPlayer) {
                long lTime = System.currentTimeMillis();
                mTvTime.setText(getString(R.string.index_zb) + TimeFormater.dateLongFormatString(lTime, TimeFormater.format2));
                mScalePanel.setTimeOffset(lTime);
                Dbug.i(tag, "lTime =" + yyyy_MMddHHmmss.format(lTime));
                mHandler.postDelayed(RTSPRunnable, 1000);
                Dbug.i(tag, "lTime =" + "---postDelayed");
            }

        }
    };


    private final Runnable RedPointRunnable = new Runnable() {
        @Override
        public void run() {
            if(mIsDevice_Recording == true){
                if(index_redpoint.getVisibility() == View.VISIBLE){
                    index_redpoint.setVisibility(View.GONE);
                }else{
                    index_redpoint.setVisibility(View.VISIBLE);
                }
                mHandler.postDelayed(RedPointRunnable,500);
            }else{
                index_redpoint.setVisibility(View.GONE);
            }

        }
    };

    public boolean getIsRecording() {
        return mIsRecording;
    }

    public boolean getIsEncording() {
        return mIsEncording;
    }

    /**
     * 监听回放状态，是否在缓冲
     * @param isBuffering
     */
    @Override
    public void onBuffering(boolean isBuffering) {
        this.isBuffering = isBuffering;
        Dbug.i(tag, "onBuffering =" + isBuffering);
        if (mSurfaceView != null) {
            mSurfaceView.updateAudioTrackPlayState(isBuffering);
        }

        if (isBuffering) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // mHandler.removeCallbacks(secondRunnable);
                    //mScalePanel.setLock(true);
                    //progressBar.setVisibility(View.VISIBLE);
                }
            });

        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //mHandler.post(secondRunnable);
                    //mScalePanel.setLock(false);
                    // progressBar.setVisibility(View.GONE);
                }
            });
        }
    }

    /**
     * 监听回放状态，已将连接
     */
    @Override
    public void onConnected() {
        bitmapInfoList.clear();
        mIsPlayBackConnected = true;
        if (isSeek)
            isSeek = false;
        if (isRequestDownload) {
            isRequestDownload = false;
            Dbug.i(tag, "---onConnected-----mStartDownloadTime:" + TimeFormater.formatYMDHMS(mStartDownloadTime) + "----mStopDownloadTime:" + TimeFormater.formatYMDHMS(mStopDownloadTime));
            mVideoManager.tryToDownload(mStartDownloadTime, mStopDownloadTime);
            return;
        }
        Dbug.i(tag, "-------------onConnected----------------------success-");
        if (!mIsFirstPlayBackConnected) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //tryToStartPlayback();
                    if (mCurrVideoInfo != null) {
                        Dbug.w(tag, "The video not exist in selected position.");
                        //mAVPlayer_back.tryToGetVideoThumbnail(AP_MODE_DEVICE_IP, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }
                }
            });
        } else {
            if (mIsStartSOS) {
                //tryToStartPlayback();
                if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                    mGetThumbnail = true;
                    String deviceip= AP_MODE_DEVICE_IP;
                    if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                        deviceip = ((MainActivity)(this.getActivity())).device_ip;
                    if(mAVPlayReal){
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }else{
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }

                }
            } else {
                //displayValueInfo(mFirstTime);
                mCurrVideoInfo = mVideoManager.getSelectedPosition(mFirstTime);
                if (mCurrVideoInfo == null) {
                    //查找最近的历史视频
                    mCurrVideoInfo = mScalePanel.getNearestVideoInfo(mFirstTime, false);
                }
                if (mAVPlayer_back != null && mCurrVideoInfo != null) {
                    mGetThumbnail = true;
                    String deviceip= AP_MODE_DEVICE_IP;
                    if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                        deviceip = ((MainActivity)(this.getActivity())).device_ip;
                    if(mAVPlayReal){
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }else{
                        mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, mCurrVideoInfo, 1, 0);
                    }
                }
            }
            mIsStartSOS = false;
            mIsFirstPlayBackConnected = false;
            mAVPlayer_back.openBuffer(false);
            if(mAVPlayReal){
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_VIDEO_PLAYBACK_SPEED, mFastForward + "");
            }else{
                ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_PLAYBACK_SPEED, mFastForward + "");
            }
        }

        if (mCurrVideoInfo != null) {
            Dbug.i(tag, "After stop cmd, then tryToGetVideoThumbnail");
            //mVideoManager.tryToGetVideoThumbnail(mCurrVideoInfo);
        } else {
            Dbug.e(tag, "tryToGetVideoThumbnail fail, mCurrVideoInfo is null");
        }

    }

    /**
     * 监听回放状态，断开连接
     */
    @Override
    public void onDisconnected() {
        mIsPlayBackConnected = false;
        Dbug.i(tag, "-------------onDisconnected-----------------------");
        progressBar.setVisibility(View.GONE);
        if (!mIsRTSPPlayer) {
            int port;
            switch (mAVPlayer_back.getPlaybackMode()){
                case PLAYBACK_MODE_FRONT:
                    port = AP_VIDEO_PORT;
                    break;
                case PLAYBACK_MODE_REAR:
                    port = AP_REAR_PLAYBACK_RTS_PORT;
                    break;
                case PLAYBACK_MODE_NOT_READY:
                default:
                    Dbug.e(tag, "playback mode not ready...");
                    return;
            }
            String deviceip= AP_MODE_DEVICE_IP;
            if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                deviceip = ((MainActivity)(this.getActivity())).device_ip;
            if (mAVPlayer_back != null && mAVPlayer_back.connect(-1, deviceip, port)) {
                Dbug.i(tag, "-------------reconnect successful--------");
            } else {
                Dbug.e(tag, "Connect fail 33");
            }
        }
    }

    /**
     * 监听回放状态，出现未知错误
     */
    @Override
    public void onError() {
        mIsPlayBackConnected = false;
        mScalePanel.setLock(false);
        int port;
        switch (mAVPlayer_back.getPlaybackMode()){
            case PLAYBACK_MODE_FRONT:
                port = AP_VIDEO_PORT;
                break;
            case PLAYBACK_MODE_REAR:
                port = AP_REAR_PLAYBACK_RTS_PORT;
                break;
            case PLAYBACK_MODE_NOT_READY:
            default:
                Dbug.e(tag, "playback mode not ready...");
                return;
        }
        String deviceip= AP_MODE_DEVICE_IP;
        if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
            deviceip = ((MainActivity)(this.getActivity())).device_ip;
        if (mAVPlayer_back != null && mAVPlayer_back.connect(-1, deviceip, port)) {
            Dbug.i(tag, "-------------reconnect successful--------");
        } else {
            Dbug.e(tag, "Connect fail 33");
        }
        progressBar.setVisibility(View.GONE);
        Dbug.i(tag, "-------------onError-----------------------");
    }

    /**
     * 监听回放中的播放状态
     * @param state
     */
    @Override
    public void onStateChanged(int state) {
        isStopped = false;
        switch (state) {
            case StreamPlayer.PlayState.PAUSE:
                Dbug.d(tag, "onStateChanged state=PAUSE");
                //isPlaying = false;
                mHandler.removeCallbacks(secondRunnable);
                isPlaying = false;
                /**Stop it when setting pause*/
                break;
            case StreamPlayer.PlayState.START:
                Dbug.d(tag, "onStateChanged state=START");
                ///mHandler.post(secondRunnable);
                //mAVPlayer_back.play();
                mHandler.post(secondRunnable);
                isPlaying = true;
                break;
            case StreamPlayer.PlayState.PLAY:
                Dbug.d(tag, "onStateChanged state=PLAY");
                mHandler.post(secondRunnable);
                isPlaying = true;
                //isPlaying = true;
                break;
            case StreamPlayer.PlayState.STOP:
                Dbug.d(tag, "onStateChanged state=STOP");
                mHandler.removeCallbacks(secondRunnable);
                //isPlaying = false;
                if (isPlaying) {
                    //tryToStartPlayback();
                }
                Dbug.d(tag, "ACTION_PLAYBACK_STATE_STOP:");
                isPlaying = false;
                isStopped = true;
                break;
            case StreamPlayer.PlayState.COMPLETION:
                Dbug.d(tag, "onStateChanged state=COMPLETION");
                mHandler.removeCallbacks(secondRunnable);
                //isPlaying = false;

                if (mAVPlayer_back != null) {
                    Dbug.i(tag, "COMPLETION : disconnect ");
                    mIsPlayBackConnected = false;
                    mAVPlayer_back.disconnect();
                }
                isPlaying = false;
                isStopped = true;
                /**Stop it when playing end */
                break;
        }
    }

    /**
     * 监听回放播放失败
     * @param s
     */
    @Override
    public void onPlayFail(String s) {

    }

    /**
     * 监听下载时候的进度
     * @param progress
     */
    @Override
    public void onProgress(float progress) {

        final float s = progress * 100;
        Dbug.i(tag, "------onProgress:" + progress);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (selectDownDialog != null && selectDownDialog.isShowing())
                    selectDownDialog.setProgress(s);
            }
        });


    }

    /**
     * 监听下载完成
     */
    @Override
    public void onCompletion() {
        Dbug.i(tag, "------onCompletion:" + "100%");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopRecording();
                isUpdataSucess = true;
                if (null != errorDialog && errorDialog.isShowing()) {

                } else {
                    if(selectDownDialog != null)
                        selectDownDialog.dismiss();
                    selectDownDialog = null;
                    if (phoDialog != null && phoDialog.isShowing()) {
                        phoDialog.dismiss();
                        phoDialog = null;
                    }
                    //showSuccessDialog();
                    showSucess();
                    PreferenceUtils.putLong(getActivity(), TIME_UPDATA_SUCESS, System.currentTimeMillis());

                }


            }
        }, 500);
        if(mAVPlayReal){
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_VIDEO_PLAYBACK_SPEED, mFastForward + "");
        }else{
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_PLAYBACK_SPEED, mFastForward + "");
        }
    }


    /**
     * 回放暂停
     */
    private void tryToPausePlayback() {
        if (mAVPlayer_back != null) {
            if (mAVPlayer_back.isPlaying()) {
                mAVPlayer_back.pause();
                onStateChanged(StreamPlayer.PlayState.PAUSE);
            }
        }
    }

    /**
     * 启动开始录制
     */
    private void tryToStartRecord(long start_time, long stop_time) {
        /**这里测试下载当前选中的文件,也可以下载指定的两个时间点的视频。真正下载动作，需要等 CMD_VIDEO_START_PLAYBACK 回复，再去调用startRecording()*/
        //mVideoManager.tryToDownload(start_time, stop_time);
        Dbug.i(tag, "------mStartDownloadTime-----:" + TimeFormater.formatYMDHMS(start_time) + "----mStopDownloadTime:" + TimeFormater.formatYMDHMS(start_time));
        mStartDownloadTime = start_time;
        mStopDownloadTime = stop_time;
        Dbug.i(tag, "mStartDownloadTime:" + TimeFormater.formatYMDHMS(mStartDownloadTime) + "----mStopDownloadTime:" + TimeFormater.formatYMDHMS(mStopDownloadTime));
        if (mAVIStreamer == null) {
            initAVIStream();
        }

        if (mAVPlayer_back != null && (mAVPlayer_back.isPaused() || mAVPlayer_back.isPlaying())) {
            mAVPlayer_back.pause();
            isRequestDownload = true;
            Dbug.i(tag, "Stop playing to record: disconnect=");
            mIsPlayBackConnected = false;
            mAVPlayer_back.disconnect();
        } else {
            if (mAVIStreamer.isRecording()) {
                stopRecording();
            } else {
                mVideoManager.tryToDownload(mStartDownloadTime, mStopDownloadTime);
            }
        }
    }


    /**
     * 真正开始录制
     */
    private void startRecording() {
        if (mAVIStreamer != null && !mAVIStreamer.isRecording()) {
            mAVIStreamer.setFilePath(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/temp");
            mTarget_PathName = "REC_" + TimeFormater.dateLongFormatString(System.currentTimeMillis(), TimeFormater.format1);
            //设置录制的时候不能缩放滑动
            mIsRecording = true;
            mIsCutRecordImage = true;
            if (mAVIStreamer != null) {
                Dbug.e(tag, "startRecording=");
                mAVPlayer_back.openBuffer(false);
                mAVIStreamer.startRecording();
            }
        } else {
            Dbug.i(tag, "Already start recording=");
        }
    }

    /**
     * 结束录制
     */
    private void stopRecording() {
        isRequestDownload = false;
        mIsRecording = false;
        if (mAVPlayer_back != null) {
            mIsPlayBackConnected = false;
            mAVPlayer_back.disconnect();
        }
        //mImPlay.setVisibility(View.GONE);
        if (mAVIStreamer != null && mAVIStreamer.isRecording()) {
            if (mAVIStreamer != null) {
                Dbug.i(tag, "----mIsRecording:" + "true");
                mAVIStreamer.stopRecording();
            }
        } else {
            Dbug.i(tag, "Already stop recording=");
        }
    }

    /**
     * 获取缩略图命令
     *
     * @param time
     */
    private void tryToGetVideoThumbnail(long time) {
        isRequestThumbnail = true;
        VideoInfo vf = mVideoManager.getSelectedPosition(time - 30000);
        if (vf == null)
            vf = mScalePanel.getNearestVideoInfo(time - 30000, true);
        if (vf != null){
            String deviceip= AP_MODE_DEVICE_IP;
            if(WifiHelper.getInstance(this.getActivity().getApplicationContext()).getWifiConnectionInfo().getSSID().contains("chainway_"))
                deviceip = ((MainActivity)(this.getActivity())).device_ip;
            if(mAVPlayReal){
                mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_REAR_PLAYBACK_THUMBNAIL_PORT, vf, 61, 1);
            }else{
                mAVPlayer_back.tryToGetVideoThumbnail(deviceip, AP_THUMBNAIL_PORT, vf, 61, 1);
            }
        }
    }

    private void goFastForward(int level) {
        if (mIsRTSPPlayer)
            return;
        if (mAVPlayer_back != null) {
            if (level == 0) {
                mAVPlayer_back.openBuffer(true);
            } else {
                mAVPlayer_back.openBuffer(false);
            }
        }
        if(mAVPlayReal){
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_REAR_VIDEO_PLAYBACK_SPEED, mFastForward + "");
        }else{
            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_PLAYBACK_SPEED, mFastForward + "");
        }
    }

    private class SosInfoAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (null != mList) {
                return mList.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity().getApplication(), R.layout.item_sos_info, null);
                holder = new ViewHolder();
                convertView.setTag(holder);
                // 给holder找view
                holder.tvData = (TextView) convertView.findViewById(R.id.item_sos_tv_data);
                holder.tvTime = (TextView) convertView.findViewById(R.id.item_sos_tv_time);
                holder.imPlay = (ImageView) convertView.findViewById(R.id.item_sos_iv);
                holder.rlDel = (RelativeLayout) convertView.findViewById(R.id.item_sos_rl_del);
                holder.llPlay = (LinearLayout) convertView.findViewById(R.id.item_sos_ll);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.imPlay.setVisibility(View.GONE);
            holder.imPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Dbug.d(tag, "recordState:" + "-----setOnClickListener-----");
                    if (mIsRecording) {
                        showToastLong(getString(R.string.index_update_video));
                        return;
                    }
                    //SOS跳转播放
                    if (mScalePanel.getVisibility() == View.GONE) {
                        //  mScalePanel.setVisibility(View.VISIBLE);
                        //   mZhiBo_Seek.setVisibility(View.GONE);
                        if (mIsRTSPPlayer == true) {
                            mIsGetSOS = false;
                            if(mAVPlayReal){
                                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_REAR_ALL_VIDEOS_INFO);
                            }else{
                                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                            }

                        }
                    }
                    mCurrVideoInfo = mList.get(position);
                    if (mIsRTSPPlayer == true) {
                        //if (mIsDevice_Recording)
                        Dbug.d(tag, "recordState:" + "---mIsDevice_Recording--setOnClickListener-----");
                        //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                        String recordState = CommunicationService.getInstance().getDeviceStatus(CMD_GET_RECORDING_STATUS);
                        Dbug.d(tag, "recordState:" + recordState);
                        if (ARGS_IN_RECORDING.equals(recordState)) {
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_STOP_RECORD, ARGS_STOP_RECORD);
                        }

                        tryToStop();
                        destroyRTSPPlayer();
                        mIsRTSPPlayer = false;
                        if (!isBrowseMode) {
                            ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_ENTER_BROWSING_MODE, ARGS_ENTER_BROWSING_MODE);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Dbug.d(tag, "recordState:" + "---sos_first--setOnClickListener-----");
                                    mIsFirstPlayBackConnected = true;
                                    mIsStartSOS = true;
                                    createBackPlayer();
                                    Dbug.d(tag, "recordState:" + "---sos_first--createBackPlayer-----");
                                    mHandler.removeCallbacks(RTSPRunnable);
                                }
                            }, 1500);

                        }
                    } else {
                        if (mAVPlayer_back != null && mAVPlayer_back.isPlaying()) {
                            //mCommandHub.sendCommand(CTP_ID_DEFAULT, CMD_VIDEO_STOP, ARGS_VIDEO_STOP);
                            Dbug.d(tag, "recordState:" + "---sos_first--connect-----");
                            mIsPlayBackConnected = false;
                            mAVPlayer_back.disconnect();
                            isPlaying = false;
                            isStopped = true;
                        } else {
                            //mAVPlayer_back.disconnect();
                            Dbug.d(tag, "recordState:" + "---sos_first--tryToStartPlayback-----");
                            tryToStartPlayback();
                            isPlaying = false;
                            isStopped = true;
                        }
                    }


                }
            });
            holder.rlDel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mIsRecording) {
                        showToastLong(getString(R.string.index_update_video));
                        return;
                    }
                    mLockSOS = mList.get(position).getFileName();
                    int index = mLockSOS.lastIndexOf(".");
                    if (index > 0) {
                        //showToastLong(mLockSOS.substring(0, index));

                        //删除SOS视频
                        /*
                        if (mApplication.getIsOffLineMode() == false) {
                            CommandHub.getInstance().sendCommand("2", "0554", mLockSOS.substring(0, index));
                        }
                        */
                        Dbug.d("TAG", "index");
                        unLockStr = mLockSOS.substring(0, index);
                        //showTwoDialog(mLockSOS.substring(0, index));
                        showTwo();
                    }
                }
            });
            holder.tvData.setText(dataSet(mList.get(position).getCreateDate(), true));
            holder.tvTime.setText(dataSet(mList.get(position).getCreateDate(), false));

            return convertView;
        }
    }

    class ViewHolder {
        TextView tvData;
        TextView tvTime;
        ImageView imPlay;
        RelativeLayout rlDel;
        LinearLayout llPlay;
    }

    private void showTwo() {
        twoDialog = new TwoDialog(getActivity(), getString(R.string.dialog_tip), getString(R.string.index_js), unLockListener);
        twoDialog.show();
    }

    private View.OnClickListener unLockListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    if (mApplication.getIsOffLineMode() == false) {
                        if (unLockStr != null)
                            ControlManager.getInstance().sendCommand("2", "0554", unLockStr);
                    }

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private void showTwoDialog(final String str) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(getActivity(), R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);
        //tvInfo.setText("确认解锁该紧急视频");
        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dialog.dismiss();
                if (mApplication.getIsOffLineMode() == false) {
                    ControlManager.getInstance().sendCommand("2", "0554", str);
                }

            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);
    }


    private Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0001:
                    //if (isSOSVisible) {
                    mLlLoadSOS.setVisibility(View.GONE);
                    mSosInfoAdapter.notifyDataSetChanged();
                    mListView.setVisibility(View.VISIBLE);
                    mLlNoVideo.setVisibility(View.GONE);
                    mRlSOS.setVisibility(View.VISIBLE);
                    //}

                    break;
                case 0002:
                    mLlLoadSOS.setVisibility(View.GONE);
                    mListView.setVisibility(View.GONE);
                    mLlNoVideo.setVisibility(View.VISIBLE);
                    mRlSOS.setVisibility(View.GONE);
                    break;
                case 1111:
                    if (null != PHO_SUCESS_PATH) {
                        mImPhoSucess.setImageBitmap(mBitmapCache.getBitmap(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo/" + PHO_SUCESS_PATH));
                    }
                    mRlPhoSucess.setVisibility(View.VISIBLE);
                    mTvPhoSucess.setText(getString(R.string.index_save_pic));
                    mBtnPhoSucess.setText(getString(R.string.index_see_pic));
                    handler1.removeMessages(1112);
                    handler1.sendEmptyMessageDelayed(1112, 2500);
                    break;
                case 1112:
                    mRlPhoSucess.setVisibility(View.GONE);
                    break;
                /*
                case 1113:
                    if (null != pd)
                        pd.dismiss();
                    if (null != VDO_SUCESS_PATH) {
                        mImPhoSucess.setImageBitmap(mBitmapCache.getBitmap(VDO_SUCESS_PATH));
                    }
                    mRlPhoSucess.setVisibility(View.VISIBLE);
                    mTvPhoSucess.setText("录像以保存到我的视频");
                    mBtnPhoSucess.setText("查看视频");
                    handler1.removeMessages(1112);
                    handler1.sendEmptyMessageDelayed(1112, 2500);
                    break;
                    */
                case 2222:
                    if (mLlLoadSOS.getVisibility() == View.VISIBLE) {
                        isSOSVisible = false;
                        mLlErrorSOS.setVisibility(View.VISIBLE);
                        mLlLoadSOS.setVisibility(View.GONE);
                        mListView.setVisibility(View.GONE);
                        mLlNoVideo.setVisibility(View.GONE);
                        mRlSOS.setVisibility(View.GONE);
                        /*
                        if (mApplication.isSdcardState()) {
                            //在线
                            mLlLoadSOS.setVisibility(View.GONE);
                            mListView.setVisibility(View.GONE);
                            mLlNoVideo.setVisibility(View.VISIBLE);
                            mRlSOS.setVisibility(View.GONE);
                        } else {
                            //不在线
                            mLlErrorSOS.setVisibility(View.VISIBLE);
                            mLlLoadSOS.setVisibility(View.GONE);
                            mListView.setVisibility(View.GONE);
                            mLlNoVideo.setVisibility(View.GONE);
                            mRlSOS.setVisibility(View.GONE);
                        }*/
                    }
                    break;
                case 3333:
                    selectUpdataDialog.setBitmapList(bitmapInfoList);
                    selectUpdataDialog.updateBitmap();
                    break;

            }
        }
    };

    private String dataSet(String data, boolean isData) {
        if (isData) {
            return data.substring(0, 4) + "-" + data.substring(4, 6) + "-" + data.substring(6, 8);
        } else {
            return data.substring(8, 10) + ":" + data.substring(10, 12) + ":" + data.substring(12, 14);
        }
    }

    private void showUpdateWindow(long start_time, long stop_time) {

        long time = (stop_time - start_time) / 1000;
        selectDownDialog = new SelectDownDialog(getActivity(), time);
        selectDownDialog.setOutsideTouchable(false);
        selectDownDialog.setCancelListener(mOncancleListener);

        selectDownDialog.showPopupWindow(mImUpdata);

    }

    final SelectDownDialog.OnCancelBtnClickListener mOncancleListener = new SelectDownDialog.OnCancelBtnClickListener() {

        @Override
        public void onCancleClick() {

            // showErrorDialog();
            showError();
        }
    };


    private void showPopupWindow(View view, long start_time, long stop_time) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.video_undata_dialog, null);
        // 设置按钮的点击事件
        TextView button = (TextView) contentView.findViewById(R.id.updata_tv_cancle);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "button is pressed",
                        Toast.LENGTH_SHORT).show();
                //showErrorDialog();
            }
        });

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);


        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.dialog_bg_pop));

        // 设置好参数之后再show
        //  popupWindow.showAsDropDown(view);

        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

    }


    /**
     * 弹出取消下载dialog
     */

    private void showError() {
        phoDialog = new PhoDialog(getActivity(), false, errorListener);
        phoDialog.show();
    }

    private View.OnClickListener errorListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    phoDialog.dismiss();
                    phoDialog = null;
                    mIsExitDownload = true;
                    stopRecording();
                    selectDownDialog.dismiss();
                    if (fileIsExists()) {
                        //存在下载完成的文件，需要删除
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                deleteFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".AVI");
                                deleteFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".JPG");
                                // deleteFilePho(mVideoPath.substring(0, mVideoPath.lastIndexOf(".")) + ".JPG");
                            }
                        }).start();
                    }

                    break;
                case R.id.dialog_btn2_rl_canale:
                    phoDialog.dismiss();
                    phoDialog = null;
                    if (isUpdataSucess) {
                        // showSuccessDialog();
                        showSucess();
                    }
                    break;
            }
        }
    };

    private void showErrorDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(getActivity(), R.layout.dialog_error_btn2,
                null);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);
        builder.setView(view);
        builder.setCancelable(false);
        errorDialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //确认删除
                mIsExitDownload = true;
                stopRecording();
                selectDownDialog.dismiss();
                errorDialog.dismiss();
                if (fileIsExists()) {
                    //存在下载完成的文件，需要删除
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            deleteFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".AVI");
                            deleteFile(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".JPG");
                            // deleteFilePho(mVideoPath.substring(0, mVideoPath.lastIndexOf(".")) + ".JPG");
                        }
                    }).start();
                }
            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //取消删除
                errorDialog.dismiss();
                //selectDownDialog.dismiss();
                if (isUpdataSucess) {
                    //showSuccessDialog();
                    showSucess();
                }
            }
        });
        errorDialog.setView(view, 0, 0, 0, 0);
        errorDialog.show();
    }

    /**
     * 弹出下载成功dialog
     */

    private void showSucess() {
        isUpdataSucess = false;
        //phoDialog = new PhoDialog(getActivity(), true, sucessListener);
        //phoDialog.show();
        progressWindow = new ProgressWindow(getActivity(),sucessListener);
        progressWindow.setOutsideTouchable(false);
        progressWindow.showPopupWindow(mScalePanel);
        progressWindow.setTvTitle(getString(R.string.dialog_updata_wait_encode));
        if(mCurrentEncodePath.equals(VDO_SUCESS_PATH)){
            progressWindow.setTvTitle(getString(R.string.dialog_updata_sucess));
            progressWindow.startProgress(1);
        }
    }

    private View.OnClickListener sucessListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.zm_rl_ok:
                    if(progressWindow.getProgress() < 100)
                        return;
                    progressWindow.dismiss();
                    if (null != VDO_SUCESS_PATH) {
                        VideoPlayDialog videoPlayDialog = VideoPlayDialog.newInstance(VDO_SUCESS_PATH);
                        //videoPlayDialog.setVideoPath(VDO_SUCESS_PATH);
                        videoPlayDialog.show(getActivity().getFragmentManager(), "VideoPlayDialog");
                    }
                    progressWindow = null;
                    break;
                case R.id.zm_rl_canale:
                    progressWindow.dismiss();
                    progressWindow = null;
                    break;
            }
        }
    };

    private void showSuccessDialog() {

        /*
        if (null != errorDialog && errorDialog.isShowing()) {
            errorDialog.dismiss();
        }
*/
        isUpdataSucess = false;
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(getActivity(), R.layout.dialog_success_btn2,
                null);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);
        builder.setView(view);
        builder.setCancelable(false);
        successDialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //查看
                successDialog.dismiss();
                //mImPlay.setVisibility(View.INVISIBLE);
                /*
                Intent intent2 = new Intent(getActivity().getApplicationContext(), VideoPlayerActivity.class);
                //intent.putExtra("video_file", allDataInfoList.get(position).getPath());
                intent2.putExtra("video_file", "0");
                //getActivity().startActivityForResult(intent, 1000);
                getActivity().startActivity(intent2);
                */

                if (null != VDO_SUCESS_PATH) {
                    VideoPlayDialog videoPlayDialog = VideoPlayDialog.newInstance(VDO_SUCESS_PATH);
                    //videoPlayDialog.setVideoPath(VDO_SUCESS_PATH);
                    videoPlayDialog.show(getActivity().getFragmentManager(), "VideoPlayDialog");
                }


            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //关闭
                successDialog.dismiss();
            }
        });
        successDialog.setView(view, 0, 0, 0, 0);
        successDialog.show();
    }

    public boolean fileIsExists() {
        try {
            File f = new File(Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video/" + mTarget_PathName + ".AVI");
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    public void deleteFile(String path) {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    public void showWaitDialog() {

        ((MainActivity) (this.getActivity())).showWaitDialog();
    }

    public void hideWaitDialog() {
        ((MainActivity) (this.getActivity())).hideWaitDialog();
    }


    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public boolean isOpenGPS(Context context) {
        LocationManager locationManager
                = (LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        if (gps ) {
            return true;
        }

        return false;
    }
}
